/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.audit.service.api.AuditService;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.generator.GetHardwareIdFailedException;
import com.koron.common.generator.InvalidSystemClockException;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.personal.domain.MyCertificate;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.api.GridNodeService;
import com.koron.scene.domain.*;
import com.koron.scene.mapper.DangerousOperationMapper;
import com.koron.scene.mapper.DangerousOperationRelationMapper;
import com.koron.scene.service.api.DangerousOperationService;
import com.koron.scene.utils.BusinessCode;
import com.koron.scene.utils.ObjectUtil;
import com.koron.system.domain.DictData;
import com.koron.system.domain.DictType;
import com.koron.system.service.api.DictTypeService;
import com.koron.workflow.service.api.WorkflowService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DangerousOperationServiceImpl implements DangerousOperationService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(DangerousOperationServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private Util util;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private GridNodeService nodeService;

    @Autowired
    private AuditService auditService;

    @Autowired
    private WorkflowService flowService;

    @Value("${app.orgCode}")
    private String orgCode;

    @Autowired
    private DictTypeService dictTypeService;

    private static Map<String, String> corpCodeMap = new HashMap<>();

    private Map<Integer, String> templateKeys = new HashMap<Integer, String>() {
        {
            this.put(1, "dangerous_operation1_creation");
            this.put(2, "dangerous_operation2_creation");
            this.put(3, "dangerous_operation3_creation");
            this.put(4, "dangerous_operation4_creation");
            this.put(5, "dangerous_operation5_creation");
            this.put(6, "dangerous_operation6_creation");
            this.put(7, "dangerous_operation7_creation");
        }
    };

    /**
     * 保存危险作业
     *
     * @param bean
     * @param user
     * @param approver
     * @param fileBean
     * @return
     */

    @Override
    public MessageBean<Integer> save(DangerousOperation bean, StaffBean user, DangerousOperationApprover approver, DangerousOperationFile fileBean) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        SessionFactory factory = new SessionFactory();
        try {
            // 新增附件管理
            manageAddFile(fileBean);
            //校验作业票
            Integer checkResult = check(bean.getOperationCategory(), bean.getOperationTicketType());
            if (checkResult == 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("作业票模板或者作业票类型不合法");
                return msg;
            }
            // 若没有申请部门信息时，默认申请部门为当前登录人所在部门
            if (StringUtils.isEmpty(bean.getApplicationUnit()) && StringUtils.isEmpty(bean.getApplicationUnitName())) {
                bean.setApplicationUnit(user.getDepartmentCode());
                bean.setApplicationUnitName(user.getDepartmentname());
            }
            // 若为外部作业人员时，提交直接改变其状态为作业中
            if (bean.getExternalWork() == 1) {
                if (bean.getStatus() == 1) {
                    bean.setStatus(2);
                }
            }
            if (StringUtils.isEmpty(bean.getId())) {
                //新增操作
                return addOperation(bean, fileBean, msg, factory, checkResult, user, approver);
            } else {
                //修改操作
                return updateOperation(bean, fileBean, msg, factory, checkResult, user, approver);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> saveByQrCode(DangerousOperation bean, StaffBean user, String approver, DangerousOperationFile fileBean) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        List<String> userIdList = new ArrayList<>();
        List<String> approverList = null;
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isNotEmpty(approver)) {
                approverList = JSONObject.parseArray(approver, String.class);
            }
            // 新增附件管理
            manageAddFile(fileBean);
            //校验作业票
            Integer checkResult = check(bean.getOperationCategory(), bean.getOperationTicketType());
            if (checkResult == 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("作业票模板或者作业票类型不合法");
                return msg;
            }
            // 若没有申请部门信息时，默认申请部门为当前登录人所在部门
            if (StringUtils.isEmpty(bean.getApplicationUnit()) && StringUtils.isEmpty(bean.getApplicationUnitName())) {
                bean.setApplicationUnit(user.getDepartmentCode());
                bean.setApplicationUnitName(user.getDepartmentname());
            }
            // 若为外部作业人员时，提交直接改变其状态为作业中
            if (bean.getExternalWork() == 1) {
                if (bean.getStatus() == 1) {
                    bean.setStatus(2);
                }
            }
            if (StringUtils.isEmpty(bean.getId())) {
                //新增操作
                return addOperationByQrCode(bean, fileBean, msg, factory, checkResult, user, approverList, userIdList);
            } else {
                //修改操作
                return updateOperationByQrCode(bean, fileBean, msg, factory, checkResult, user, approverList, userIdList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    private MessageBean<Integer> updateOperationByQrCode(DangerousOperation bean, DangerousOperationFile fileBean, MessageBean<Integer> msg, SessionFactory factory, Integer checkResult, StaffBean user, List<String> approverList, List<String> userIdList) throws Exception {
        DangerousOperation entity = factory.getMapper(DangerousOperationMapper.class).queryOne(bean.getId());
        if (null == entity) {
            factory.close();
            msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
            msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
            return msg;
        }
        if (entity.getStatus() != 0) {
            factory.close();
            msg.setCode(BusinessCode.NON_DRAFT_CANNOT_EDIT.getCode());
            msg.setDescription("非草稿状态不能编辑");
            return msg;
        }
        // 要保留的附件管理
        manageKeepFile(fileBean);
        List<String> keepList = fileBean.getKeepList();
        if (null != keepList && keepList.size() > 0) {
            bean.setAttachment(new Gson().toJson(keepList));
        }
        List<String> keepPreviewList = fileBean.getKeepPreviewList();
        if (null != keepPreviewList && keepPreviewList.size() > 0) {
            bean.setPreviewAttachment(new Gson().toJson(keepPreviewList));
        }
        List<String> operationApplicantList = fileBean.getOperationApplicantList();
        if (null != operationApplicantList && operationApplicantList.size() > 0) {
            bean.setOperationApplicantSignature(new Gson().toJson(operationApplicantList));
        }
        List<String> operationExecutorList = fileBean.getOperationExecutorList();
        if (null != operationExecutorList && operationExecutorList.size() > 0) {
            bean.setOperationExecutorSignature(new Gson().toJson(operationExecutorList));
        }
        List<String> hoistingCommanderList = fileBean.getHoistingCommanderList();
        if (null != hoistingCommanderList && hoistingCommanderList.size() > 0) {
            bean.setHoistingCommanderSignature(new Gson().toJson(hoistingCommanderList));
        }
        List<String> operationSupervisorList = fileBean.getOperationSupervisorList();
        if (null != operationSupervisorList && operationSupervisorList.size() > 0) {
            bean.setOperationSupervisorSignature(new Gson().toJson(operationSupervisorList));
        }
        List<String> personInChargeList = fileBean.getPersonInChargeList();
        if (null != personInChargeList && personInChargeList.size() > 0) {
            bean.setPersonInChargeSignature(new Gson().toJson(personInChargeList));
        }
        List<String> analystList = fileBean.getAnalystList();
        if (null != analystList && analystList.size() > 0) {
            bean.setAnalystSignature(new Gson().toJson(analystList));
        }
        List<String> educatedPersonList = fileBean.getEducatedPersonList();
        if (null != educatedPersonList && educatedPersonList.size() > 0) {
            bean.setEducatedPersonSignature(new Gson().toJson(educatedPersonList));
        }
        List<String> educatingPeopleList = fileBean.getEducatingPeopleList();
        if (null != educatingPeopleList && educatingPeopleList.size() > 0) {
            bean.setEducatingPeopleSignature(new Gson().toJson(educatingPeopleList));
        }
        List<String> powerSupplyPersonList = fileBean.getPowerSupplyPersonList();
        if (null != powerSupplyPersonList && powerSupplyPersonList.size() > 0) {
            bean.setPowerSupplyPersonSignature(new Gson().toJson(powerSupplyPersonList));
        }
        List<String> powerCutPersonList = fileBean.getPowerCutPersonList();
        if (null != powerCutPersonList && powerCutPersonList.size() > 0) {
            bean.setPowerCutPersonSignature(new Gson().toJson(powerCutPersonList));
        }
        List<String> completionConfirmerList = fileBean.getCompletionConfirmerList();
        if (null != completionConfirmerList && completionConfirmerList.size() > 0) {
            bean.setCompletionConfirmerSignature(new Gson().toJson(completionConfirmerList));
        }
        List<String> managementUnitHeadList = fileBean.getManagementUnitHeadList();
        if (null != managementUnitHeadList && managementUnitHeadList.size() > 0) {
            bean.setManagementUnitHeadSignature(new Gson().toJson(managementUnitHeadList));
        }
        List<String> sceneSafetyManagementList = fileBean.getSceneSafetyManagementList();
        if (null != sceneSafetyManagementList && sceneSafetyManagementList.size() > 0) {
            bean.setSceneSafetyManagementSignature(new Gson().toJson(sceneSafetyManagementList));
        }
        List<String> companyChairmanList = fileBean.getCompanyChairmanList();
        if (null != companyChairmanList && companyChairmanList.size() > 0) {
            bean.setCompanyChairmanSignature(new Gson().toJson(companyChairmanList));
        }
        Integer value = factory.getMapper(DangerousOperationMapper.class).update(bean);
        if (value > 0) {
            value = updateRelation(bean, factory, value);
        }
        if (value > 0) {
            if (bean.getExternalWork() == 0 && bean.getStatus() == 1) {
                // 启动流程
                String templateKey = getTemplateKeyByQrCode(checkResult);
                if (null == templateKey) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("未找到流程模板");
                    return msg;
                }
                Boolean flag = startAuditByQrCode(bean, user, approverList, "流程待审批", "危险作业流程", templateKey);
                if (!flag) {
                    deleteKeepFile(fileBean);
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("危险作业流程启动失败");
                    return msg;
                } else {
                    deleteDelFile(fileBean);
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("危险作业提交成功");
                    return msg;
                }
            }
            deleteDelFile(fileBean);
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("危险作业保存成功");
            return msg;
        } else {
            deleteKeepFile(fileBean);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("危险作业修改失败");
            return msg;
        }
    }

    private MessageBean<Integer> addOperationByQrCode(DangerousOperation bean, DangerousOperationFile fileBean, MessageBean<Integer> msg, SessionFactory factory, Integer checkResult, StaffBean user, List<String> approverList, List<String> userIdList) throws Exception {
        // 获取编码
        String code = getCode(factory);
        bean.setOperationCode(code);
        bean.setId(DefaultIdGenerator.getInstance().generateLongId());
        bean.setAddTime(bean.getUpdateTime());
        bean.setAddUser(bean.getUpdateUser());
        bean.setAddUserName(bean.getUpdateUserName());
        List<String> keepList = fileBean.getKeepList();
        if (null != keepList && keepList.size() > 0) {
            bean.setAttachment(new Gson().toJson(keepList));
        }
        List<String> keepPreviewList = fileBean.getKeepPreviewList();
        if (null != keepPreviewList && keepPreviewList.size() > 0) {
            bean.setPreviewAttachment(new Gson().toJson(keepPreviewList));
        }
        List<String> operationApplicantList = fileBean.getOperationApplicantList();
        if (null != operationApplicantList && operationApplicantList.size() > 0) {
            bean.setOperationApplicantSignature(new Gson().toJson(operationApplicantList));
        }
        List<String> operationExecutorList = fileBean.getOperationExecutorList();
        if (null != operationExecutorList && operationExecutorList.size() > 0) {
            bean.setOperationExecutorSignature(new Gson().toJson(operationExecutorList));
        }
        List<String> hoistingCommanderList = fileBean.getHoistingCommanderList();
        if (null != hoistingCommanderList && hoistingCommanderList.size() > 0) {
            bean.setHoistingCommanderSignature(new Gson().toJson(hoistingCommanderList));
        }
        List<String> operationSupervisorList = fileBean.getOperationSupervisorList();
        if (null != operationSupervisorList && operationSupervisorList.size() > 0) {
            bean.setOperationSupervisorSignature(new Gson().toJson(operationSupervisorList));
        }
        List<String> personInChargeList = fileBean.getPersonInChargeList();
        if (null != personInChargeList && personInChargeList.size() > 0) {
            bean.setPersonInChargeSignature(new Gson().toJson(personInChargeList));
        }
        List<String> analystList = fileBean.getAnalystList();
        if (null != analystList && analystList.size() > 0) {
            bean.setAnalystSignature(new Gson().toJson(analystList));
        }
        List<String> educatedPersonList = fileBean.getEducatedPersonList();
        if (null != educatedPersonList && educatedPersonList.size() > 0) {
            bean.setEducatedPersonSignature(new Gson().toJson(educatedPersonList));
        }
        List<String> educatingPeopleList = fileBean.getEducatingPeopleList();
        if (null != educatingPeopleList && educatingPeopleList.size() > 0) {
            bean.setEducatingPeopleSignature(new Gson().toJson(educatingPeopleList));
        }
        List<String> powerSupplyPersonList = fileBean.getPowerSupplyPersonList();
        if (null != powerSupplyPersonList && powerSupplyPersonList.size() > 0) {
            bean.setPowerSupplyPersonSignature(new Gson().toJson(powerSupplyPersonList));
        }
        List<String> powerCutPersonList = fileBean.getPowerCutPersonList();
        if (null != powerCutPersonList && powerCutPersonList.size() > 0) {
            bean.setPowerCutPersonSignature(new Gson().toJson(powerCutPersonList));
        }
        List<String> completionConfirmerList = fileBean.getCompletionConfirmerList();
        if (null != completionConfirmerList && completionConfirmerList.size() > 0) {
            bean.setCompletionConfirmerSignature(new Gson().toJson(completionConfirmerList));
        }
        List<String> managementUnitHeadList = fileBean.getManagementUnitHeadList();
        if (null != managementUnitHeadList && managementUnitHeadList.size() > 0) {
            bean.setManagementUnitHeadSignature(new Gson().toJson(managementUnitHeadList));
        }
        List<String> sceneSafetyManagementList = fileBean.getSceneSafetyManagementList();
        if (null != sceneSafetyManagementList && sceneSafetyManagementList.size() > 0) {
            bean.setSceneSafetyManagementSignature(new Gson().toJson(sceneSafetyManagementList));
        }
        List<String> companyChairmanList = fileBean.getCompanyChairmanList();
        if (null != companyChairmanList && companyChairmanList.size() > 0) {
            bean.setCompanyChairmanSignature(new Gson().toJson(companyChairmanList));
        }
        Integer value = factory.getMapper(DangerousOperationMapper.class).insert(bean);
        if (value > 0) {
            value = insertRelation(bean, factory, value);
        }
        if (value > 0) {
            if (bean.getExternalWork() == 0 && bean.getStatus() == 1) {
                // 启动流程
                String templateKey = getTemplateKeyByQrCode(checkResult);
                if (null == templateKey) {
                    factory.close();
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("未找到流程模板");
                    return msg;
                }
                Boolean flag = startAuditByQrCode(bean, user, approverList, "流程待审批", "危险作业提交流程", templateKey);
                if (!flag) {
                    deleteKeepFile(fileBean);
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("危险作业流程启动失败");
                    return msg;
                } else {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("危险作业提交成功");
                    msg.setData(value);
                    return msg;
                }
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("危险作业保存成功");
            return msg;
        } else {
            deleteKeepFile(fileBean);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    /**
     * 危险作业相关信息新增保存
     *
     * @param bean
     * @param factory
     * @param value
     * @return
     * @throws InvalidSystemClockException
     * @throws GetHardwareIdFailedException
     */
    public Integer insertRelation(DangerousOperation bean, SessionFactory factory, Integer value) throws InvalidSystemClockException, GetHardwareIdFailedException, IOException {
        DangerousOperationRelationMapper mapper = factory.getMapper(DangerousOperationRelationMapper.class);
        List<SafetyMeasure> safetyMeasureList = bean.getSafetyMeasureList();
        List<BlindPlate> blindPlateList = bean.getBlindPlateList();
        List<HotWork> hotWorkList = bean.getHotWorkList();
        List<OperationType> operationTypeList = bean.getOperationTypeList();
        List<PersonalProtectionAndEmergency> personalProtectionAndEmergencyList = bean.getPersonalProtectionAndEmergencyList();
        List<GasDetection> gasDetectionList = bean.getGasDetectionList();
        List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = bean.getRiskIdentificationAndMeasuresList();
        if (null != safetyMeasureList && safetyMeasureList.size() > 0) {
            for (SafetyMeasure safetyMeasure : safetyMeasureList) {
                List<MultipartFile> files = safetyMeasure.getFiles();
                if (null != files && files.size() > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        safetyMeasure.getKeepList().add(url + "#" + fileName);
                        File previewFile = docConverterUtils.converter(file);
                        if (previewFile != null) {
                            String previewFilePath = clientWrapper.uploadFile(new FileInputStream(previewFile), previewFile.length(), FilenameUtils.getExtension(previewFile.getName()));
                            safetyMeasure.getKeepPreviewList().add(previewFilePath);
                        } else {
                            safetyMeasure.getKeepPreviewList().add(null);
                        }
                    }
                }
                List<String> keepList = safetyMeasure.getKeepList();
                if (null != keepList && keepList.size() > 0) {
                    safetyMeasure.setAttachment(new Gson().toJson(keepList));
                }
                List<String> keepPreviewList = safetyMeasure.getKeepPreviewList();
                if (null != keepPreviewList && keepPreviewList.size() > 0) {
                    safetyMeasure.setPreviewAttachment(new Gson().toJson(keepPreviewList));
                }
                safetyMeasure.setId(DefaultIdGenerator.getInstance().generateLongId());
                safetyMeasure.setDangerousOperationId(bean.getId());
                safetyMeasure.setOperationCategory(bean.getOperationCategory());
                safetyMeasure.setOperationTicketType(bean.getOperationTicketType());
            }
            value = mapper.batchInsertSafe(safetyMeasureList);
        }
        if (null != operationTypeList && operationTypeList.size() > 0) {
            for (OperationType operationType : operationTypeList) {
                operationType.setId(DefaultIdGenerator.getInstance().generateLongId());
                operationType.setDangerousOperationId(bean.getId());
                operationType.setOperationCategory(bean.getOperationCategory());
                operationType.setOperationTicketType(bean.getOperationTicketType());
            }
            value = mapper.batchInsertType(operationTypeList);
        }
        if (null != personalProtectionAndEmergencyList && personalProtectionAndEmergencyList.size() > 0) {
            for (PersonalProtectionAndEmergency protectionAndEmergency : personalProtectionAndEmergencyList) {
                protectionAndEmergency.setId(DefaultIdGenerator.getInstance().generateLongId());
                protectionAndEmergency.setDangerousOperationId(bean.getId());
                protectionAndEmergency.setOperationCategory(bean.getOperationCategory());
                protectionAndEmergency.setOperationTicketType(bean.getOperationTicketType());
            }
            value = mapper.batchInsertPersonal(personalProtectionAndEmergencyList);
        }
        if (null != gasDetectionList && gasDetectionList.size() > 0) {
            for (GasDetection gasDetection : gasDetectionList) {
                gasDetection.setId(DefaultIdGenerator.getInstance().generateLongId());
                gasDetection.setDangerousOperationId(bean.getId());
                gasDetection.setOperationCategory(bean.getOperationCategory());
                gasDetection.setOperationTicketType(bean.getOperationTicketType());
            }
            value = mapper.batchInsertGas(gasDetectionList);
        }
        if (null != riskIdentificationAndMeasuresList && riskIdentificationAndMeasuresList.size() > 0) {
            for (RiskIdentificationAndMeasures measures : riskIdentificationAndMeasuresList) {
                List<MultipartFile> files = measures.getFiles();
                if (null != files && files.size() > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        measures.getKeepList().add(url + "#" + fileName);
                        File previewFile = docConverterUtils.converter(file);
                        if (previewFile != null) {
                            String previewFilePath = clientWrapper.uploadFile(new FileInputStream(previewFile), previewFile.length(), FilenameUtils.getExtension(previewFile.getName()));
                            measures.getKeepPreviewList().add(previewFilePath);
                        } else {
                            measures.getKeepPreviewList().add(null);
                        }
                    }
                }
                List<String> keepList = measures.getKeepList();
                if (null != keepList && keepList.size() > 0) {
                    measures.setAttachment(new Gson().toJson(keepList));
                }
                List<String> keepPreviewList = measures.getKeepPreviewList();
                if (null != keepPreviewList && keepPreviewList.size() > 0) {
                    measures.setPreviewAttachment(new Gson().toJson(keepPreviewList));
                }
                measures.setId(DefaultIdGenerator.getInstance().generateLongId());
                measures.setDangerousOperationId(bean.getId());
                measures.setOperationCategory(bean.getOperationCategory());
                measures.setOperationTicketType(bean.getOperationTicketType());
            }
            value = mapper.batchInsertRisk(riskIdentificationAndMeasuresList);
        }
        if (null != blindPlateList && blindPlateList.size() > 0) {
            for (BlindPlate plate : blindPlateList) {
                plate.setId(DefaultIdGenerator.getInstance().generateLongId());
                plate.setDangerousOperationId(bean.getId());
            }
            value = mapper.batchInsertBlindPlate(blindPlateList);
        }
        if (null != hotWorkList && hotWorkList.size() > 0) {
            for (HotWork hotWork : hotWorkList) {
                hotWork.setId(DefaultIdGenerator.getInstance().generateLongId());
                hotWork.setDangerousOperationId(bean.getId());
            }
            value = mapper.batchInsertHotWork(hotWorkList);
        }
        return value;
    }


    /**
     * 更新危险作业相关信息
     *
     * @param bean
     * @param factory
     * @param value
     * @return
     * @throws InvalidSystemClockException
     * @throws GetHardwareIdFailedException
     */
    public Integer updateRelation(DangerousOperation bean, SessionFactory factory, Integer value) throws InvalidSystemClockException, GetHardwareIdFailedException, IOException {
        List<SafetyMeasure> safetyMeasures = bean.getSafetyMeasureList();
        List<OperationType> operationTypeList = bean.getOperationTypeList();
        List<PersonalProtectionAndEmergency> personalProtectionAndEmergencyList = bean.getPersonalProtectionAndEmergencyList();
        List<GasDetection> gasDetectionList = bean.getGasDetectionList();
        List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = bean.getRiskIdentificationAndMeasuresList();
        List<BlindPlate> blindPlateList = bean.getBlindPlateList();
        List<HotWork> hotWorkList = bean.getHotWorkList();
        if (null != safetyMeasures && safetyMeasures.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deleteSafeByDangerousOperationId(bean.getId());
            for (SafetyMeasure safetyMeasure : safetyMeasures) {
                List<MultipartFile> files = safetyMeasure.getFiles();
                if (null != files && files.size() > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        safetyMeasure.getKeepList().add(url + "#" + fileName);
                        File previewFile = docConverterUtils.converter(file);
                        if (previewFile != null) {
                            String previewFilePath = clientWrapper.uploadFile(new FileInputStream(previewFile), previewFile.length(), FilenameUtils.getExtension(previewFile.getName()));
                            safetyMeasure.getKeepPreviewList().add(previewFilePath);
                        } else {
                            safetyMeasure.getKeepPreviewList().add(null);
                        }
                    }
                }
                // 保留的附件地址
                String keepFiles = safetyMeasure.getKeepFiles();
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[,，]");
                    safetyMeasure.getKeepList().addAll(Arrays.asList(keepArray));
                }
                // 保留的附件预览地址
                String keepPreviewFiles = safetyMeasure.getKeepPreviewFiles();
                if (StringUtils.isNotEmpty(keepPreviewFiles)) {
                    String[] keepPreview = keepPreviewFiles.split("[,，]");
                    safetyMeasure.getKeepPreviewList().addAll(Arrays.asList(keepPreview));
                }
                List<String> keepList = safetyMeasure.getKeepList();
                if (null != keepList && keepList.size() > 0) {
                    safetyMeasure.setAttachment(new Gson().toJson(keepList));
                }
                List<String> keepPreviewList = safetyMeasure.getKeepPreviewList();
                if (null != keepPreviewList && keepPreviewList.size() > 0) {
                    safetyMeasure.setPreviewAttachment(new Gson().toJson(keepPreviewList));
                }
                String delFiles = safetyMeasure.getDelFiles();
                if (StringUtils.isNotEmpty(delFiles)) {
                    clientWrapper.deleteFile(delFiles);
                }
                String delPreviewFiles = safetyMeasure.getDelPreviewFiles();
                if (StringUtils.isNotEmpty(delPreviewFiles)) {
                    clientWrapper.deleteFile(delPreviewFiles);
                }
                safetyMeasure.setId(DefaultIdGenerator.getInstance().generateLongId());
                safetyMeasure.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertSafe(safetyMeasures);
        }
        if (null != operationTypeList && operationTypeList.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deleteTypeByDangerousOperationId(bean.getId());
            for (OperationType operationType : operationTypeList) {
                operationType.setId(DefaultIdGenerator.getInstance().generateLongId());
                operationType.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertType(operationTypeList);
        }
        if (null != personalProtectionAndEmergencyList && personalProtectionAndEmergencyList.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deletePersonByDangerousOperationId(bean.getId());
            for (PersonalProtectionAndEmergency protectionAndEmergency : personalProtectionAndEmergencyList) {
                protectionAndEmergency.setId(DefaultIdGenerator.getInstance().generateLongId());
                protectionAndEmergency.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertPersonal(personalProtectionAndEmergencyList);
        }
        if (null != gasDetectionList && gasDetectionList.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deleteGasByDangerousOperationId(bean.getId());
            for (GasDetection gasDetection : gasDetectionList) {
                gasDetection.setId(DefaultIdGenerator.getInstance().generateLongId());
                gasDetection.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertGas(gasDetectionList);
        }
        if (null != riskIdentificationAndMeasuresList && riskIdentificationAndMeasuresList.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deleteRiskByDangerousOperationId(bean.getId());
            for (RiskIdentificationAndMeasures measures : riskIdentificationAndMeasuresList) {
                List<MultipartFile> files = measures.getFiles();
                if (null != files && files.size() > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        measures.getKeepList().add(url + "#" + fileName);
                        File previewFile = docConverterUtils.converter(file);
                        if (previewFile != null) {
                            String previewFilePath = clientWrapper.uploadFile(new FileInputStream(previewFile), previewFile.length(), FilenameUtils.getExtension(previewFile.getName()));
                            measures.getKeepPreviewList().add(previewFilePath);
                        } else {
                            measures.getKeepPreviewList().add(null);
                        }
                    }
                }
                // 保留的附件地址
                String keepFiles = measures.getKeepFiles();
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[,，]");
                    measures.getKeepList().addAll(Arrays.asList(keepArray));
                }
                // 保留的附件预览地址
                String keepPreviewFiles = measures.getKeepPreviewFiles();
                if (StringUtils.isNotEmpty(keepPreviewFiles)) {
                    String[] keepPreview = keepPreviewFiles.split("[,，]");
                    measures.getKeepPreviewList().addAll(Arrays.asList(keepPreview));
                }
                List<String> keepList = measures.getKeepList();
                if (null != keepList && keepList.size() > 0) {
                    measures.setAttachment(new Gson().toJson(keepList));
                }
                List<String> keepPreviewList = measures.getKeepPreviewList();
                if (null != keepPreviewList && keepPreviewList.size() > 0) {
                    measures.setPreviewAttachment(new Gson().toJson(keepPreviewList));
                }
                String delFiles = measures.getDelFiles();
                if (StringUtils.isNotEmpty(delFiles)) {
                    clientWrapper.deleteFile(delFiles);
                }
                String delPreviewFiles = measures.getDelPreviewFiles();
                if (StringUtils.isNotEmpty(delPreviewFiles)) {
                    clientWrapper.deleteFile(delPreviewFiles);
                }
                measures.setId(DefaultIdGenerator.getInstance().generateLongId());
                measures.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertRisk(riskIdentificationAndMeasuresList);
        }
        if (null != blindPlateList && blindPlateList.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deleteBlindPlateByDangerousOperationId(bean.getId());
            for (BlindPlate plate : blindPlateList) {
                plate.setId(DefaultIdGenerator.getInstance().generateLongId());
                plate.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertBlindPlate(blindPlateList);
        }
        if (null != hotWorkList && hotWorkList.size() > 0) {
            //先删除原有的数据，再重新添加
            factory.getMapper(DangerousOperationRelationMapper.class).deleteHotWorkByDangerousOperationId(bean.getId());
            for (HotWork hotWork : hotWorkList) {
                hotWork.setId(DefaultIdGenerator.getInstance().generateLongId());
                hotWork.setDangerousOperationId(bean.getId());
            }
            value = factory.getMapper(DangerousOperationRelationMapper.class).batchInsertHotWork(hotWorkList);
        }
        return value;
    }


    /**
     * 操作失败，删除新增的附件
     *
     * @param keepList         保存的附件地址集合
     * @param keepFiles        保存的附件地址
     * @param keepPreviewList  保存的附件预览地址集合
     * @param keepPreviewFiles 保存的附件预览地址
     */
    public void rollBakFile(List<String> keepList, String keepFiles, List<String> keepPreviewList, String keepPreviewFiles) {
        if (null != keepList && keepList.size() > 0) {
            if (StringUtils.isEmpty(keepFiles)) {
                for (String url : keepList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            } else {
                List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                for (String url : keepList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            }
        }
        if (null != keepPreviewList && keepPreviewList.size() > 0) {
            if (StringUtils.isEmpty(keepPreviewFiles)) {
                for (String url : keepPreviewList) {
                    //获取文件后缀名
                    String substring = url.substring(url.lastIndexOf(".") + 1);
                    boolean contains = Lists.newArrayList("pdf", "PDF").contains(substring);
                    if (contains) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                List<String> keeps = Arrays.asList(keepPreviewFiles.split("[,，]"));
                for (String pdfUrl : keepPreviewList) {
                    if (!keeps.contains(pdfUrl)) {
                        //获取文件后缀名
                        String substring = pdfUrl.substring(pdfUrl.lastIndexOf(".") + 1);
                        boolean contains = Lists.newArrayList("pdf", "PDF").contains(substring);
                        if (contains) {
                            clientWrapper.deleteFile(pdfUrl.split("#")[0]);
                        }
                    }
                }
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(String id, StaffBean user) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            DangerousOperationRelationMapper relationMapper = factory.getMapper(DangerousOperationRelationMapper.class);
            DangerousOperation dangerousOperation = mapper.queryOne(id);
            List<String> fileList = new ArrayList<>();
            if (null == dangerousOperation) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                return msg;
            }
            if (dangerousOperation.getStatus() != 0) {
                msg.setCode(BusinessCode.NON_DRAFT_CANNOT_DELETE.getCode());
                msg.setDescription(BusinessCode.NON_DRAFT_CANNOT_DELETE.getDescription());
                return msg;
            }
            // 查找安全措施信息
            List<SafetyMeasure> safetyMeasureList = relationMapper.getSafetyByDangerousId(id);
            if (null != safetyMeasureList && safetyMeasureList.size() > 0) {
                safetyMeasureList.forEach(safetyMeasure -> {
                    if (StringUtils.isNotEmpty(safetyMeasure.getAttachment())) {
                        fileList.add(safetyMeasure.getAttachment());
                    }
                    if (StringUtils.isNotEmpty(safetyMeasure.getPreviewAttachment())) {
                        fileList.add(safetyMeasure.getPreviewAttachment());
                    }
                });
                relationMapper.deleteSafeByDangerousOperationId(id);
            }
            // 查找作业类型信息
            List<OperationType> operationTypeList = relationMapper.getTypeByDangerousId(id);
            if (null != operationTypeList && operationTypeList.size() > 0) {
                relationMapper.deleteTypeByDangerousOperationId(id);
            }
            // 查找个人防护及应急措施信息
            List<PersonalProtectionAndEmergency> personalProtectionAndEmergencyList = relationMapper.getPersonByDangerousId(id);
            if (null != personalProtectionAndEmergencyList && personalProtectionAndEmergencyList.size() > 0) {
                relationMapper.deletePersonByDangerousOperationId(id);
            }
            //查找气体检测信息
            List<GasDetection> gasDetectionList = relationMapper.getGasByDangerousId(id);
            if (null != gasDetectionList && gasDetectionList.size() > 0) {
                relationMapper.deleteGasByDangerousOperationId(id);
            }
            // 查找风险识别及防范措施
            List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = relationMapper.getRiskByDangerousId(id);
            if (null != riskIdentificationAndMeasuresList && riskIdentificationAndMeasuresList.size() > 0) {
                riskIdentificationAndMeasuresList.forEach(riskIdentificationAndMeasures -> {
                    if (StringUtils.isNotEmpty(riskIdentificationAndMeasures.getAttachment())) {
                        fileList.add(riskIdentificationAndMeasures.getAttachment());
                    }
                    if (StringUtils.isNotEmpty(riskIdentificationAndMeasures.getPreviewAttachment())) {
                        fileList.add(riskIdentificationAndMeasures.getPreviewAttachment());
                    }
                });
                relationMapper.deleteRiskByDangerousOperationId(id);
            }
            List<HotWork> hotWorkList = relationMapper.getHotWorkByDangerousId(id);
            if (null != hotWorkList && hotWorkList.size() > 0) {
                relationMapper.deleteHotWorkByDangerousOperationId(id);
            }
            List<BlindPlate> blindPlateList = relationMapper.getBlindPlateByDangerousId(id);
            if (null != blindPlateList && blindPlateList.size() > 0) {
                relationMapper.deleteBlindPlateByDangerousOperationId(id);
            }
            Integer delete = mapper.delete(id);
            if (delete > 0) {
                deleteFileList(fileList, dangerousOperation);
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                factory.close();
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                factory.close(false);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            logger.error(e.getMessage(),e);
            return msg;
        }
    }

    private void deleteFileList(List<String> fileList, DangerousOperation dangerousOperation) {
        fileList.add(dangerousOperation.getSceneSafetyManagementSignature());
        fileList.add(dangerousOperation.getSupervisorSignature());
        fileList.add(dangerousOperation.getAnalystSignature());
        fileList.add(dangerousOperation.getOperationSupervisorSignature());
        fileList.add(dangerousOperation.getOperationExecutorSignature());
        fileList.add(dangerousOperation.getCompanyChairmanSignature());
        fileList.add(dangerousOperation.getCompletionConfirmerSignature());
        fileList.add(dangerousOperation.getEducatingPeopleSignature());
        fileList.add(dangerousOperation.getEducatedPersonSignature());
        fileList.add(dangerousOperation.getHoistingCommanderSignature());
        fileList.add(dangerousOperation.getOperationApplicantSignature());
        fileList.add(dangerousOperation.getManagementUnitHeadSignature());
        fileList.add(dangerousOperation.getPowerSupplyPersonSignature());
        fileList.add(dangerousOperation.getPowerCutPersonSignature());
        fileList.add(dangerousOperation.getPersonInChargeSignature());
        fileList.forEach(this::deleteFile);
    }

    @Override
    public MessageBean<DangerousOperationBean> queryOne(String id) {
        MessageBean<DangerousOperationBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "获取详情成功", DangerousOperationBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            DangerousOperationRelationMapper relationMapper = factory.getMapper(DangerousOperationRelationMapper.class);
            DangerousOperation dangerousOperation = mapper.queryOne(id);
            if (null == dangerousOperation) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                return msg;
            }
            // 查找作业类型信息
            List<OperationType> operationTypeList = relationMapper.getTypeByDangerousId(id);
            if (null != operationTypeList && operationTypeList.size() > 0) {
                dangerousOperation.setOperationTypeList(operationTypeList);
            }
            // 查找安全措施信息
            List<SafetyMeasure> safetyMeasureList = relationMapper.getSafetyByDangerousId(id);
            if (null != safetyMeasureList && safetyMeasureList.size() > 0) {
                for (SafetyMeasure safetyMeasure : safetyMeasureList) {
                    safetyMeasure.setEditStatus(true);
                }
                dangerousOperation.setSafetyMeasureList(safetyMeasureList);
            }
            //查找气体检测信息
            List<GasDetection> gasDetectionList = relationMapper.getGasByDangerousId(id);
            if (null != gasDetectionList && gasDetectionList.size() > 0) {
                for (GasDetection gasDetection : gasDetectionList) {
                    if (StringUtils.isNotEmpty(gasDetection.getDetectionTime())) {
                        gasDetection.setDetectionTime(sdf.format(sdf.parse(gasDetection.getDetectionTime())));
                    }
                }
                dangerousOperation.setGasDetectionList(gasDetectionList);
            }
            // 查找风险识别及防范措施
            List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = relationMapper.getRiskByDangerousId(id);
            if (null != riskIdentificationAndMeasuresList && riskIdentificationAndMeasuresList.size() > 0) {
                if (dangerousOperation.getOperationCategory() == 0 && dangerousOperation.getOperationTicketType() == 9) {
                    riskIdentificationAndMeasuresList.forEach(risk -> {
                        if (risk.getSortNo() <= 5) {
                            risk.setRiskType("生产风险");
                        } else {
                            risk.setRiskType("作业风险");
                        }
                    });
                }
                dangerousOperation.setRiskIdentificationAndMeasuresList(riskIdentificationAndMeasuresList);
            }
            // 查找个人防护及应急措施信息
            List<PersonalProtectionAndEmergency> protectionAndEmergencyList = relationMapper.getPersonByDangerousId(id);
            if (null != protectionAndEmergencyList && protectionAndEmergencyList.size() > 0) {
                dangerousOperation.setPersonalProtectionAndEmergencyList(protectionAndEmergencyList);
            }
            List<BlindPlate> blindPlateList = relationMapper.getBlindPlateByDangerousId(id);
            if (null != blindPlateList && blindPlateList.size() > 0) {
                dangerousOperation.setBlindPlateList(blindPlateList);
            }
            List<HotWork> hotWorkList = relationMapper.getHotWorkByDangerousId(id);
            if (null != hotWorkList && hotWorkList.size() > 0) {
                dangerousOperation.setHotWorkList(hotWorkList);
            }
            if (StringUtils.isNotEmpty(dangerousOperation.getCorpCode())) {
                CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(dangerousOperation.getCorpCode());
                dangerousOperation.setCorpName(corpBean == null ? null : corpBean.getCorpName());
            }
            if (StringUtils.isEmpty(dangerousOperation.getProjectId()) && StringUtils.isEmpty(dangerousOperation.getProjectName())) {
                dangerousOperation.setProjectId("");
                dangerousOperation.setProjectName("");
            }
            DangerousOperationBean bean = new DangerousOperationBean();
            BeanUtils.copyProperties(dangerousOperation, bean);
            // 获取流程信息
            if (bean.getStatus() != 0) {
                // 获取流程模板
                Integer check = check(bean.getOperationCategory(), bean.getOperationTicketType());
                String templateKey = getTemplateKey(check);
                List<DangerousOperationFlowNode> nodes = getWorkFlowMessage(id, bean.getUpdateTime());
                // 设置作业票流程信息
                setWorkFlowMessage(nodes, bean, templateKey);
                if (bean.getOperationCategory() == 3 && StringUtils.isEmpty(bean.getOperatorsName())) {
                    bean.setOperatorsName(dangerousOperation.getOperationExecutorName());
                }
            }
            msg.setData(bean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 设置表单流程节点信息
     *
     * @param nodes
     * @param bean
     * @param templateKey
     */
    private void setWorkFlowMessage(List<DangerousOperationFlowNode> nodes, DangerousOperationBean bean, String templateKey) {
        try {
            if (null != nodes && nodes.size() > 0) {
                // 流程1
                if (templateKeys.get(1).equals(templateKey)) {
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setResponsiblePersonName(node.getOperationUserName());
                            bean.setResponsiblePersonCommit(node.getComment());
                            bean.setResponsiblePersonTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setWorkPermitName(node.getOperationUserName());
                            bean.setWorkPermitCommit(node.getComment());
                            bean.setWorkPermitTime(node.getOperationTime());
                        } else if ("Process-task3".equals(node.getNodeId())) {
                            bean.setWorkGuardianName(node.getOperationUserName());
                            bean.setWorkGuardianCommit(node.getComment());
                            bean.setWorkGuardianTime(node.getOperationTime());
                        } else if ("Process-task4".equals(node.getNodeId())) {
                            bean.setWorkTicketIssuerName(node.getOperationUserName());
                            bean.setWorkTicketIssuerCommit(node.getComment());
                            bean.setWorkTicketIssuerTime(node.getOperationTime());
                        }
                    }
                } else if (templateKeys.get(2).equals(templateKey)) {
                    // 流程二
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setDeviceSpecificResponsibilityName(node.getOperationUserName());
                            bean.setDeviceSpecificResponsibilityCommit(node.getComment());
                            bean.setDeviceSpecificResponsibilityTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setRegionalHeadName(node.getOperationUserName());
                            bean.setRegionalHeadCommit(node.getComment());
                            bean.setRegionalHeadTime(node.getOperationTime());
                        } else if ("Process-task3".equals(node.getNodeId())) {
                            bean.setSafetyManagerName(node.getOperationUserName());
                            bean.setSafetyManagerCommit(node.getComment());
                            bean.setSafetyManagerTime(node.getOperationTime());
                        } else if ("Process-task4".equals(node.getNodeId())) {
                            bean.setFactoryDirectorName(node.getOperationUserName());
                            bean.setFactoryDirectorCommit(node.getComment());
                            bean.setFactoryDirectorTime(node.getOperationTime());
                        }
                    }
                } else if (templateKeys.get(3).equals(templateKey)) {
                    // 流程三
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setRegionalHeadName(node.getOperationUserName());
                            bean.setRegionalHeadCommit(node.getComment());
                            bean.setRegionalHeadTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setSafetyManagerName(node.getOperationUserName());
                            bean.setSafetyManagerCommit(node.getComment());
                            bean.setSafetyManagerTime(node.getOperationTime());
                        } else if ("Process-task3".equals(node.getNodeId())) {
                            bean.setFactoryDirectorName(node.getOperationUserName());
                            bean.setFactoryDirectorCommit(node.getComment());
                            bean.setFactoryDirectorTime(node.getOperationTime());
                        }
                    }
                } else if (templateKeys.get(4).equals(templateKey)) {
                    // 流程四
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setBranchOfficeName(node.getOperationUserName());
                            bean.setBranchOfficeCommit(node.getComment());
                            bean.setBranchOfficeTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setSafetyManagementDepartmentName(node.getOperationUserName());
                            bean.setSafetyManagementDepartmentCommit(node.getComment());
                            bean.setSafetyManagementDepartmentTime(node.getOperationTime());
                        }
                    }
                } else if (templateKeys.get(5).equals(templateKey)) {
                    // 流程五
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setProjectSafetyOfficerName(node.getOperationUserName());
                            bean.setProjectSafetyOfficerCommit(node.getComment());
                            bean.setProjectSafetyOfficerTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setBranchOfficeName(node.getOperationUserName());
                            bean.setBranchOfficeCommit(node.getComment());
                            bean.setBranchOfficeTime(node.getOperationTime());
                        }
                    }
                } else if (templateKeys.get(6).equals(templateKey)) {
                    // 流程六
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setOperatorsName(node.getOperationUserName());
                            bean.setOperatorsCommit(node.getComment());
                            bean.setOperatorsTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setSiteSafetyExecutiveName(node.getOperationUserName());
                            bean.setSiteSafetyExecutiveCommit(node.getComment());
                            bean.setSiteSafetyExecutiveTime(node.getOperationTime());
                        } else if ("Process-task3".equals(node.getNodeId())) {
                            bean.setPrincipalPersonName(node.getOperationUserName());
                            bean.setPrincipalPersonCommit(node.getComment());
                            bean.setPrincipalPersonTime(node.getOperationTime());
                        } else if ("Process-task4".equals(node.getNodeId())) {
                            bean.setChairmanName(node.getOperationUserName());
                            bean.setChairmanCommit(node.getComment());
                            bean.setChairmanTime(node.getOperationTime());
                        }
                    }
                } else if (templateKeys.get(7).equals(templateKey)) {
                    // 流程7
                    for (DangerousOperationFlowNode node : nodes) {
                        if ("Process-task1".equals(node.getNodeId())) {
                            bean.setOperatorsName(node.getOperationUserName());
                            bean.setOperatorsCommit(node.getComment());
                            bean.setOperatorsTime(node.getOperationTime());
                        } else if ("Process-task2".equals(node.getNodeId())) {
                            bean.setSiteSafetyExecutiveName(node.getOperationUserName());
                            bean.setSiteSafetyExecutiveCommit(node.getComment());
                            bean.setSiteSafetyExecutiveTime(node.getOperationTime());
                        } else if ("Process-task3".equals(node.getNodeId())) {
                            bean.setPrincipalPersonName(node.getOperationUserName());
                            bean.setPrincipalPersonCommit(node.getComment());
                            bean.setPrincipalPersonTime(node.getOperationTime());
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public MessageBean<Integer> disclosure(SessionFactory factory, StaffBean user, String id, MultipartFile[] disclosureFiles) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "交底操作成功", Integer.class);
        try {
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            DangerousOperation dangerousOperation = mapper.queryOne(id);
            if (null == dangerousOperation) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                return msg;
            }
            if (dangerousOperation.getStatus() != 5) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("非交底状态下的危险作业无法进行交底操作");
                return msg;
            }
            List<String> keepList = new ArrayList<>();
            if (null != disclosureFiles && disclosureFiles.length > 0) {
                for (MultipartFile file : disclosureFiles) {
                    String url = clientWrapper.uploadFile(file);
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    keepList.add(url + "#" + fileName);
                }
            }
            if (null != keepList && keepList.size() > 0) {
                dangerousOperation.setDisclosureAttachment(new Gson().toJson(keepList));
            }
            // 交底将状态改为2
            dangerousOperation.setStatus(2);
            Integer update = mapper.update(dangerousOperation);
            if (update <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("交底操作失败");
                return msg;
            }
            factory.close();
            msg.setData(update);
            return msg;
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            factory.close();
        }
    }


    /**
     * 作业票确认完工
     *
     * @param user
     * @param id
     * @param completionDescription
     * @param completionTime
     * @param personInCharge
     * @param personInChargeName
     * @param completionConfirmer
     * @param completionConfirmerName
     * @return
     */
    @Override
    public MessageBean<Integer> confirm(StaffBean user, String id, String completionDescription, String completionTime, String personInCharge, String personInChargeName, String completionConfirmer, String completionConfirmerName) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "确认完工成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            DangerousOperation dangerousOperation = mapper.queryOne(id);
            if (null == dangerousOperation) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                factory.close();
                return msg;
            }
            if (dangerousOperation.getStatus() != 2) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("非进行中状态下的危险作业无法确认完工");
                factory.close();
                return msg;
            }
            if (StringUtils.isNotEmpty(personInCharge) && StringUtils.isNotEmpty(personInChargeName)) {
                dangerousOperation.setPersonInCharge(personInCharge);
                dangerousOperation.setPersonInChargeName(personInChargeName);
            }
            if (StringUtils.isEmpty(completionConfirmer) && StringUtils.isEmpty(completionConfirmerName)) {
                dangerousOperation.setCompletionConfirmer(user.getCode());
                dangerousOperation.setCompletionConfirmerName(user.getName());
            } else {
                dangerousOperation.setCompletionConfirmer(completionConfirmer);
                dangerousOperation.setCompletionConfirmerName(completionConfirmerName);
            }
            dangerousOperation.setCompletionTime(completionTime);
            dangerousOperation.setCompletionDescription(completionDescription);
            // 确定完工将状态改为3
            dangerousOperation.setStatus(3);
            Integer update = mapper.update(dangerousOperation);
            if (update <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("确认完工失败");
                return msg;
            }
            factory.close();
            msg.setData(update);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 危险作业统计分析，根据公司，危险作业状态，时间段进行统计危险作业次数
     * 统计各类型在不同状态下的数量
     *
     * @param corpCode  公司
     * @param status    状态
     * @param startTime 统计开始时间
     * @param endTime   统计截止时间
     * @return
     */
    @Override
    public MessageBean<List<DangerousOperationAnalysisBean>> dangerousOperationAnalysis(String corpCode, Integer status, String startTime, String endTime) {
        MessageBean<List<DangerousOperationAnalysisBean>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<DangerousOperationAnalysisBean> list = new ArrayList<>();
            //未传入code时，查询所有
            if (StringUtils.isEmpty(corpCode)) {
                generateDangerAnalysis(list, factory, null, status, startTime, endTime);
            } else {
                //查询指定code的直接下属部门
                List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(corpCode, 0).getData();
                if (null != departmentTreeBeanList && departmentTreeBeanList.size() > 1) {
                    for (int i = 1; i < departmentTreeBeanList.size(); i++) {
                        DepartmentTreeBean departmentTreeBean = departmentTreeBeanList.get(i);
                        generateDangerAnalysis(list, factory, departmentTreeBean, status, startTime, endTime);
                    }
                } else {
                    //没有下级部门，直接返回当前部门的数据
                    if (departmentTreeBeanList.size() == 1) {
                        generateDangerAnalysis(list, factory, departmentTreeBeanList.get(0), status, startTime, endTime);
                    }
                    if (null != list && list.size() > 0) {
                        for (DangerousOperationAnalysisBean bean : list) {
                            bean.setExistChild(0);
                        }
                    }
                }
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("危险作业统计成功");
            msg.setData(list);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 危险作业统计分析，根据公司，时间段进行统计危险作业次数
     * 统计各状态的数量
     *
     * @param corpCode  公司
     * @param startTime 统计开始时间
     * @param endTime   统计截止时间
     * @return
     */
    @Override
    public MessageBean<List<DangerousOperationAnalysis>> analysis(String corpCode, String startTime, String endTime) {
        MessageBean<List<DangerousOperationAnalysis>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<DangerousOperationAnalysis> list = new ArrayList<>();
            //未传入code时，查询所有
            if (StringUtils.isEmpty(corpCode)) {
                dangerousOperationAnalysis(list, factory, null, startTime, endTime);
            } else {
                //查询指定code的直接下属部门
                List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(corpCode, 0).getData();
                if (null != departmentTreeBeanList && departmentTreeBeanList.size() > 1) {
                    for (int i = 1; i < departmentTreeBeanList.size(); i++) {
                        DepartmentTreeBean departmentTreeBean = departmentTreeBeanList.get(i);
                        dangerousOperationAnalysis(list, factory, departmentTreeBean, startTime, endTime);
                    }
                } else {
                    //没有下级部门，直接返回当前部门的数据
                    if (departmentTreeBeanList.size() == 1) {
                        dangerousOperationAnalysis(list, factory, departmentTreeBeanList.get(0), startTime, endTime);
                    }
                    if (null != list && list.size() > 0) {
                        for (DangerousOperationAnalysis bean : list) {
                            bean.setExistChild(0);
                        }
                    }
                }
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("危险作业统计成功");
            msg.setData(list);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 获取危险作业流程历史审批轨迹节点信息
     * 用于导出
     *
     * @param id
     * @param updateTime
     * @return
     */
    @Override
    public List<DangerousOperationFlowNode> getFlowMessage(String id, Date updateTime) {
        try {
            List<DangerousOperationFlowNode> nodeList = new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            // 根据业务id和更新时间来获取审批Audit数据
            List<String> idLists = new ArrayList<>();
            idLists.add(id);
            Audit audit = auditService.queryByBusinessIds(new Gson().toJson(idLists), updateTime);
            // 获取流程审批历史轨迹
            MessageBean<?> history = flowService.history(audit.getSetCode(), audit.getTemplateKey(), audit.getId());
            if (0 == history.getCode() && history.getData() != null) {
                List<Map> historys = (List<Map>) history.getData();
                if (historys != null && historys.size() > 0) {
                    for (Map map : historys) {
                        DangerousOperationFlowNode node = new DangerousOperationFlowNode();
                        String nowNodeId = map.get("nowNodeId").toString();
                        String nodeName = map.get("nowNodeName").toString();
                        String operationUser = map.get("operationUser").toString();
                        String operationUserName = map.get("operationUserName").toString();
                        String operation = map.get("operation").toString();
                        String operationTime = map.get("operationTime").toString();
                        String comment = map.get("comment").toString();
                        node.setNodeId(nowNodeId);
                        node.setNodeName(nodeName);
                        node.setOperationUser(operationUser);
                        node.setOperationUserName(operationUserName);
                        Date operationDate = df.parse(operationTime);
                        node.setOperation(operation);
                        node.setOperationTime(operationTime);
                        node.setComment(comment);
                        nodeList.add(node);
                    }
                }
            }
            // 获取已审的审批节点
            Set<String> stringSet = nodeList.stream().map(dangerousOperationFlowNode -> dangerousOperationFlowNode.getNodeId()).collect(Collectors.toSet());
            // 获取各审批节点的数据并将相同节点的所有审批信息数据整合在一起
            for (String nodeId : stringSet) {
                StringBuilder nameAndTime = new StringBuilder();
                for (DangerousOperationFlowNode node : nodeList) {
                    if (node.getNodeId().equals(nodeId)) {
                        nameAndTime.append(node.getOperationUserName()).append("(").append(node.getOperationTime()).append(")").append(node.getOperation()).append(" ");
                    }
                }
                nodeList.stream().filter(flowNode -> flowNode.getNodeId().equals(nodeId)).forEach(node -> node.setOperationUserAndTime(nameAndTime.toString()));
            }
            return nodeList;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    /**
     * 获取危险作业流程历史审批轨迹节点信息
     * 用于查询详情
     *
     * @param id
     * @param updateTime
     * @return
     */
    public List<DangerousOperationFlowNode> getWorkFlowMessage(String id, Date updateTime) {
        try {
            List<DangerousOperationFlowNode> nodeList = new ArrayList<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            // 根据业务id和更新时间来获取审批Audit数据
            List<String> idLists = new ArrayList<>();
            idLists.add(id);
            Audit audit = auditService.queryByBusinessIds(new Gson().toJson(idLists), updateTime);
            if (null != audit) {
                // 获取流程审批历史轨迹
                MessageBean<?> history = flowService.history(audit.getSetCode(), audit.getTemplateKey(), audit.getId());
                if (0 == history.getCode() && history.getData() != null) {
                    List<Map> historys = (List<Map>) history.getData();
                    if (historys != null && historys.size() > 0) {
                        for (Map map : historys) {
                            DangerousOperationFlowNode node = new DangerousOperationFlowNode();
                            String nowNodeId = map.get("nowNodeId").toString();
                            String nodeName = map.get("nowNodeName").toString();
                            String operationUser = map.get("operationUser").toString();
                            String operationUserName = map.get("operationUserName").toString();
                            String operation = map.get("operation").toString();
                            String operationTime = map.get("operationTime").toString();
                            String comment = map.get("comment").toString();
                            node.setNodeId(nowNodeId);
                            node.setNodeName(nodeName);
                            node.setOperationUser(operationUser);
                            node.setOperationUserName(operationUserName);
                            Date operationDate = df.parse(operationTime);
                            node.setOperationDate(operationDate);
                            node.setOperation(operation);
                            node.setOperationTime(operationTime);
                            node.setComment(comment);
                            if (null != nodeList && nodeList.size() > 0) {
                                int count = 0;
                                for (DangerousOperationFlowNode flowNode : nodeList) {
                                    if (flowNode.getNodeId().equals(nowNodeId)) {
                                        if (flowNode.getOperationDate().before(operationDate)) {
                                            flowNode.setOperation(operation);
                                            flowNode.setNodeName(nodeName);
                                            flowNode.setOperationUser(operationUser);
                                            flowNode.setOperationUserName(operationUserName);
                                            flowNode.setOperationTime(operationTime);
                                            flowNode.setOperationDate(operationDate);
                                            flowNode.setComment(comment);
                                        }
                                    } else {
                                        count++;
                                    }
                                }
                                if (count == nodeList.size()) {
                                    nodeList.add(node);
                                }
                            } else {
                                nodeList.add(node);
                            }
                        }
                    }
                }
            }
            return nodeList;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<Integer> delay(StaffBean user, String id, Date delayDate, String delayDescription, DangerousOperationApprover approver) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "延期成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            DangerousOperation dangerousOperation = mapper.queryOne(id);
            if (null == dangerousOperation) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                factory.close();
                return msg;
            }
            if (dangerousOperation.getStatus() != 2) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("非进行中状态下的危险作业无法延期");
                factory.close();
                return msg;
            }
            if (null != dangerousOperation.getOperationEndTime()) {
                if (delayDate.before(dangerousOperation.getOperationEndTime())) {
                    msg.setCode(BusinessCode.DELAY_DATE_BEFORE_END_TIME.getCode());
                    msg.setDescription(BusinessCode.DELAY_DATE_BEFORE_END_TIME.getDescription());
                    factory.close();
                    return msg;
                }
            }
            dangerousOperation.setDelayDate(delayDate);
            //设置为延期
            dangerousOperation.setDelay(1);
            dangerousOperation.setDelayDescription(delayDescription);
            // 改变状态为4，延期申请中
            dangerousOperation.setStatus(4);
            Integer update = mapper.update(dangerousOperation);
            if (update > 0) {
//                if (dangerousOperation.getIsMobile() == 0) {
                // 获取流程模板
                Integer checkResult = check(dangerousOperation.getOperationCategory(), dangerousOperation.getOperationTicketType());
                String auditTemplateKey = getTemplateKey(checkResult);
                Boolean flag = startAudit(dangerousOperation, user, approver, "流程待审批", "危险作业延期申请流程", auditTemplateKey);
                if (!flag) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("危险作业流程启动失败");
                    return msg;
                } else {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("危险作业提交延期成功");
                    return msg;
                }
//                } else {
//                    factory.close();
//                    msg.setCode(BusinessCode.SUCCESS.getCode());
//                    msg.setDescription("危险作业提交延期成功");
//                    return msg;
//                }
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("作业延期失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    private void dangerousOperationAnalysis(List<DangerousOperationAnalysis> operationAnalysisBeanList, SessionFactory factory, DepartmentTreeBean departmentTreeBean, String startTime, String endTime) {
        //查询当前部门下的所有网格（包括网格和部门）,不包含自己本身
        List<String> codeList = new ArrayList<>();
        if (departmentTreeBean != null) {
            codeList = nodeService.getChildCodeList(departmentTreeBean.getDepartmentCode());
            if (codeList == null) {
                codeList = new ArrayList<>();
            }
            codeList.add(departmentTreeBean.getDepartmentCode());
        }
        // 获取审批中的危险作业数据
        DangerousOperationAnalysis operationAnalysis = factory.getMapper(DangerousOperationMapper.class).getAnalysis(codeList, startTime, endTime);
        operationAnalysis.setCorpCode(departmentTreeBean == null ? "776B361BFFAC4F00BBF459CD1303A8B2" : departmentTreeBean.getDepartmentCode());
        operationAnalysis.setCorpName(departmentTreeBean == null ? "水之眼" : departmentTreeBean.getName());
        operationAnalysisBeanList.add(operationAnalysis);
    }

    /**
     * 查新当前部门下的所有危险作业统计数量
     *
     * @param operationAnalysisBeanList
     * @param factory
     * @param departmentTreeBean
     * @param status
     * @param startTime
     * @param endTime
     */
    private void generateDangerAnalysis(List<DangerousOperationAnalysisBean> operationAnalysisBeanList, SessionFactory factory, DepartmentTreeBean departmentTreeBean, Integer status, String startTime, String endTime) {
        //查询当前部门下的所有网格（包括网格和部门）,不包含自己本身
        List<String> codeList = new ArrayList<>();
        List<DangerousOperationAnalysisBean> list = new ArrayList<>();
        if (departmentTreeBean != null) {
            codeList = nodeService.getChildCodeList(departmentTreeBean.getDepartmentCode());
            if (codeList == null) {
                codeList = new ArrayList<>();
            }
            codeList.add(departmentTreeBean.getDepartmentCode());
        }
        if (null == status) { //未传入状态时，查询所有非草稿状态的数据
            // 获取审批中的危险作业数据
            DangerousOperationAnalysisBean operationAnalysis1 = factory.getMapper(DangerousOperationMapper.class).getAnalysisByStatus(codeList, 1, startTime, endTime);
            operationAnalysis1.setStatus(1);
            // 获取作业中的危险作业数据
            DangerousOperationAnalysisBean operationAnalysis2 = factory.getMapper(DangerousOperationMapper.class).getAnalysisByStatus(codeList, 2, startTime, endTime);
            operationAnalysis2.setStatus(2);
            // 获取已完成的危险做而已数据
            DangerousOperationAnalysisBean operationAnalysis3 = factory.getMapper(DangerousOperationMapper.class).getAnalysisByStatus(codeList, 3, startTime, endTime);
            operationAnalysis3.setStatus(3);
            list.add(operationAnalysis1);
            list.add(operationAnalysis2);
            list.add(operationAnalysis3);
        } else {
            // 传了状态参数时，查询指定状态的统计数据
            DangerousOperationAnalysisBean operationAnalysis = factory.getMapper(DangerousOperationMapper.class).getAnalysisByStatus(codeList, status, startTime, endTime);
            operationAnalysis.setStatus(status);
            list.add(operationAnalysis);
        }
        for (DangerousOperationAnalysisBean bean : list) {
            bean.setCorpCode(departmentTreeBean == null ? "776B361BFFAC4F00BBF459CD1303A8B2" : departmentTreeBean.getDepartmentCode());
            bean.setCorpName(departmentTreeBean == null ? "水之眼" : departmentTreeBean.getName());
        }
        operationAnalysisBeanList.addAll(list);
    }

    @Override
    public MessageBean<DataBean<DangerousOperation>> list(String corpCode, String operationCategory, String operationTicketType, String operationCategoryName, String operationTicketTypeName, String operationCode, Integer status, String startTime, String endTime, Integer start, Integer rows, String keyword) {
        MessageBean<DataBean<DangerousOperation>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            rows = (rows == null || rows <= 0) ? 1 : rows;
            String codes = util.getCodes(corpCode);
            List<DangerousOperation> list = factory.getMapper(DangerousOperationMapper.class).queryByCondition(codes, operationCategory, operationTicketType, operationCategoryName, operationTicketTypeName, operationCode, status, startTime, endTime, start, rows, keyword);
            Integer totalNumber = factory.getMapper(DangerousOperationMapper.class).countByCondition(codes, operationCategory, operationTicketType, operationCategoryName, operationTicketTypeName, operationCode, status, startTime, endTime, keyword);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<DangerousOperation> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询危险作业列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List<DangerousOperation>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    for (String id : idList) {
                        DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
                        DangerousOperation dangerousOperation = mapper.queryOne(id);
                        List<DangerousOperation> dangerousOperationList = new ArrayList<>();
                        dangerousOperationList.add(dangerousOperation);
                        msg.setCode(BusinessCode.SUCCESS.getCode());
                        msg.setDescription(BusinessCode.SUCCESS.getDescription());
                        msg.setData(dangerousOperationList);
                    }
                }
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("id不能为空");
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    /**
     * 根据危险作业分类和作业票类型查询安全防范措施
     *
     * @param operationCategory   作业票分类
     * @param operationTicketType 作业票类型
     * @return
     */
    @Override
    public MessageBean<List<SafetyMeasure>> getAllSafetyMeasure(Integer operationCategory, Integer operationTicketType) {
        MessageBean<List<SafetyMeasure>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<SafetyMeasure> list = factory.getMapper(DangerousOperationMapper.class).getAllSafetyMeasureByCondition(operationCategory, operationTicketType);
            if (null == list || list.size() <= 0) {
                msg.setData(new ArrayList<>());
            } else {
                for (SafetyMeasure safetyMeasure : list) {
                    safetyMeasure.setEditStatus(true);
                }
                msg.setData(list);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询安全防范措施信息成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 根据危险作业分类和作业票类型查询风险隐患和防范措施接口
     *
     * @param operationCategory   危险作业分类
     * @param operationTicketType 作业票类型
     * @return
     */
    @Override
    public MessageBean<List<RiskIdentificationAndMeasures>> getAllRiskIdentificationAndMeasures(Integer operationCategory, Integer operationTicketType) {
        MessageBean<List<RiskIdentificationAndMeasures>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<RiskIdentificationAndMeasures> list = factory.getMapper(DangerousOperationMapper.class).getAllRiskIdentificationAndMeasuresByCondition(operationCategory, operationTicketType);
            if (null == list || list.size() <= 0) {
                msg.setData(new ArrayList<>());
            } else {
                if (operationCategory == 0 && operationTicketType == 9) {
                    list.forEach(risk -> {
                        if (risk.getSortNo() <= 5) {
                            risk.setRiskType("生产风险");
                        } else {
                            risk.setRiskType("作业风险");
                        }
                    });
                }
                msg.setData(list);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询风险隐患和防范措施信息成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 根据危险作业分类和作业票类型查询作业类型
     *
     * @param operationCategory   危险作业分类
     * @param operationTicketType 作业票类型
     * @return
     */
    @Override
    public MessageBean<List<OperationType>> getAllOperationType(Integer operationCategory, Integer operationTicketType) {
        MessageBean<List<OperationType>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<OperationType> list = factory.getMapper(DangerousOperationMapper.class).getAllOperationTypeByCondition(operationCategory, operationTicketType);
            if (null == list || list.size() <= 0) {
                msg.setData(new ArrayList<>());
            } else {
                msg.setData(list);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询作业类型信息成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 根据危险作业分类和作业票类型查询个人防护及措施接口
     *
     * @param operationCategory   危险作业分类
     * @param operationTicketType 作业票类型
     * @return
     */
    @Override
    public MessageBean<List<PersonalProtectionAndEmergency>> getAllProtectionAndEmergency(Integer operationCategory, Integer operationTicketType) {
        MessageBean<List<PersonalProtectionAndEmergency>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<PersonalProtectionAndEmergency> list = factory.getMapper(DangerousOperationMapper.class).getAllProtectionAndEmergencyByCondition(operationCategory, operationTicketType);
            if (null == list || list.size() <= 0) {
                msg.setData(new ArrayList<>());
            } else {
                msg.setData(list);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询个人防护及应急措施信息成功");
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 危险作业导出获取详情
     *
     * @param id 危险作业id
     * @return
     */
    @Override
    public MessageBean<DangerousOperationVo> getDangerousOperation(String id) {
        MessageBean<DangerousOperationVo> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "获取详情成功", DangerousOperationVo.class);
        try (SessionFactory factory = new SessionFactory()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            DangerousOperationRelationMapper relationMapper = factory.getMapper(DangerousOperationRelationMapper.class);
            DangerousOperationVo operation = mapper.getDangerousOperation(id);
            if (null == operation) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                return msg;
            }
            // 查找作业类型信息
            List<OperationType> operationTypeList = relationMapper.getTypeByDangerousId(id);
            if (null != operationTypeList && operationTypeList.size() > 0) {
                operation.setOperationTypeList(operationTypeList);
            }
            // 查找安全措施信息
            List<SafetyMeasure> safetyMeasureList = relationMapper.getSafetyByDangerousId(id);
            if (null != safetyMeasureList && safetyMeasureList.size() > 0) {
                operation.setSafetyMeasureList(safetyMeasureList);
            }
            //查找气体检测信息
            List<GasDetection> gasDetectionList = relationMapper.getGasByDangerousId(id);
            if (null != gasDetectionList && gasDetectionList.size() > 0) {
                for (GasDetection gasDetection : gasDetectionList) {
                    gasDetection.setDetectionTime(format.format(sdf.parse(gasDetection.getDetectionTime())));
                }
                operation.setGasDetectionList(gasDetectionList);
            }
            // 查找风险识别及防范措施
            List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = relationMapper.getRiskByDangerousId(id);
            if (null != riskIdentificationAndMeasuresList && riskIdentificationAndMeasuresList.size() > 0) {
                operation.setRiskIdentificationAndMeasuresList(riskIdentificationAndMeasuresList);
            }
            // 查找个人防护及应急措施信息
            List<PersonalProtectionAndEmergency> protectionAndEmergencyList = relationMapper.getPersonByDangerousId(id);
            if (null != protectionAndEmergencyList && protectionAndEmergencyList.size() > 0) {
                operation.setPersonalProtectionAndEmergencyList(protectionAndEmergencyList);
            }
            if (StringUtils.isNotEmpty(operation.getCorpCode())) {
                CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(operation.getCorpCode());
                operation.setCorpName(corpBean == null ? null : corpBean.getCorpName());
            }
            List<BlindPlate> blindPlateList = relationMapper.getBlindPlateByDangerousId(id);
            if (null != blindPlateList && blindPlateList.size() > 0) {
                operation.setBlindPlateList(blindPlateList);
            }
            List<HotWork> hotWorkList = relationMapper.getHotWorkByDangerousId(id);
            if (null != hotWorkList && hotWorkList.size() > 0) {
                operation.setHotWorkList(hotWorkList);
            }
            //当状态为非草稿状态时，导出流程中数据；
            if (operation.getStatus() != 0) {
                List<DangerousOperationFlowNode> flowMessage = getFlowMessage(id, operation.getUpdateTime());
                if (null == flowMessage) {
                    flowMessage = new ArrayList<>();
                }
                if (operation.getOperationCategory() == 3) {
                    List<String> collect = flowMessage.stream().map(node -> node.getNodeId()).collect(Collectors.toList());
                    if (!collect.contains("Process-task1")) {
                        DangerousOperationFlowNode node = new DangerousOperationFlowNode();
                        node.setNodeId("Process-task1");
                        node.setOperationUserAndTime(operation.getOperationExecutorName());
                        flowMessage.add(node);
                    }
//                    if (!collect.contains("Process-task2")) {
//                        DangerousOperationFlowNode node = new DangerousOperationFlowNode();
//                        node.setNodeId("Process-task2");
//                        node.setOperationUserAndTime(operation.getSceneSafetyManagementName());
//                        flowMessage.add(node);
//                    }
//                    if (!collect.contains("Process-task3")) {
//                        DangerousOperationFlowNode node = new DangerousOperationFlowNode();
//                        node.setNodeId("Process-task3");
//                        node.setOperationUserAndTime(operation.getManagementUnitHeadName());
//                        flowMessage.add(node);
//                    }
//                    if (!collect.contains("Process-task4")) {
//                        DangerousOperationFlowNode node = new DangerousOperationFlowNode();
//                        node.setNodeId("Process-task4");
//                        node.setOperationUserAndTime(operation.getCompanyChairmanName());
//                        flowMessage.add(node);
//                    }
                }
                operation.setNodeList(flowMessage);
                if (operation.getStatus() == 3) {
                    StringBuilder sb = new StringBuilder();
                    String completionTime = sdf.format(sdf.parse(operation.getCompletionTime()));
                    StringBuilder confirmerAndTime = sb.append(operation.getCompletionConfirmerName().split("_")[0]).append("(").append(completionTime).append(")");
                    operation.setCompletionConfirmerAndTime(confirmerAndTime.toString());
                }
            }
            if (null != operation.getAddTime()) {
                operation.setAddTimeStr(format.format(operation.getAddTime()));
            }
            if (null != operation.getOperationStartTime()) {
                operation.setOperationStartTimeStr(format.format(operation.getOperationStartTime()));
            }
            if (null != operation.getOperationEndTime()) {
                operation.setOperationEndTimeStr(format.format(operation.getOperationEndTime()));
            }
            if (null != operation.getPowerSupplyTime()) {
                operation.setPowerSupplyTimeStr(format.format(operation.getPowerSupplyTime()));
            }
            if (null != operation.getPowerCutTime()) {
                operation.setPowerCutTimeStr(format.format(operation.getPowerCutTime()));
            }
            if (null != operation.getSamplingDetectionTime()) {
                operation.setSamplingDetectionTimeStr(format.format(operation.getSamplingDetectionTime()));
            }
            if (null != operation.getCompletionTime()) {
                Date parse = sdf.parse(operation.getCompletionTime());
                operation.setCompletionTimeStr(format.format(parse));
            }
            if (null != operation.getDelayDate()) {
                operation.setDelayDateStr(format.format(operation.getDelayDate()));
            }
            msg.setData(operation);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 根据作业模板分类和作业票类型计算对应的作业票
     *
     * @param category 作业分类 0-海宜专用，1-模板1，2-模板2
     * @param type     作业票类型
     * @return
     */
    @Override
    public Integer check(Integer category, Integer type) {
        if (category == 0) {
            switch (type) {
                case 1:
                    //海宜公司临时用电作业
                    return 1;
                case 2:
                    //海宜公司受限空间作业
                    return 2;
                case 3:
                    //海宜公司起重吊装作业
                    return 3;
                case 4:
                    //海宜公司动火作业
                    return 4;
                case 5:
                    //海宜公司破土作业
                    return 5;
                case 6:
                    //海宜公司高处作业
                    return 6;
                case 7:
                    //海宜公司抽堵盲板作业
                    return 7;
                case 9:
                    //海宜公司断路作业
                    return 8;
            }
        } else if (category == 1) {
            switch (type) {
                case 1:
                    //模板1临时用电作业
                    return 9;
                case 2:
                    //模板1受限空间作业
                    return 10;
                case 3:
                    //模板1吊装作业
                    return 11;
                case 4:
                    //模板1动火作业
                    return 12;
                case 6:
                    //模板1高处作业
                    return 13;
            }
        } else if (category == 2) {
            switch (type) {
                case 1:
                    //模板2临时用电作业
                    return 14;
                case 2:
                    //模板2有限空间作业
                    return 15;
                case 3:
                    //模板2起重吊装作业
                    return 16;
                case 4:
                    //模板2施工现场动火作业
                    return 17;
                case 5:
                    //模板2破土作业
                    return 18;
                case 6:
                    //模板2高空作业
                    return 19;
                case 7:
                    //模板2抽堵盲板作业
                    return 20;
                case 8:
                    //模板2设备检修安全作业
                    return 21;
                case 9:
                    //模板2断路安全作业
                    return 22;
            }
        } else if (category == 3) {
            switch (type) {
                case 1:
                    //供水临时用电作业
                    return 23;
                case 2:
                    //供水有限空间作业
                    return 24;
                case 3:
                    //供水起重吊装作业
                    return 25;
                case 4:
                    //供水动火作业
                    return 26;
                case 5:
                    //供水动土作业
                    return 27;
                case 6:
                    //供水高空作业
                    return 28;
                case 7:
                    //供水抽堵盲板作业
                    return 29;
                case 9:
                    //供水断路安全作业
                    return 30;
            }
        }
        return 0;
    }


    /**
     * 根据作业票模板结果找到对应用的流程模板
     *
     * @param checkResult
     * @return
     */
//    private String getAuditTemplateKey(Integer checkResult) {
//        if (checkResult >= 1 && checkResult <= 8) {
//            return "dangerous_operation1_creation";
//        } else if (checkResult > 8 && checkResult <= 13) {
//            if (checkResult > 8 && checkResult < 12) {
//                return "dangerous_operation15_creation";
//            } else if (checkResult == 12) {
//                return "dangerous_operation9_creation";
//            } else if (checkResult == 13) {
//                return "dangerous_operation16_creation";
//            }
//        } else if (checkResult > 13 && checkResult <= 22) {
//            if (checkResult == 14) {
//                return "dangerous_operation3_creation";
//            } else if (checkResult == 15) {
//                return "dangerous_operation4_creation";
//            } else if (checkResult == 16 || checkResult == 19) {
//                return "dangerous_operation5_creation";
//            } else if (checkResult == 17) {
//                return "dangerous_operation6_creation，dangerous_operation7_creation";
//            } else if (checkResult == 18) {
//                return "dangerous_operation8_creation";
//            } else if (checkResult == 20) {
//                return "dangerous_operation10_creation";
//            } else if (checkResult == 21) {
//                return "dangerous_operation11_creation";
//            } else {
//                return "dangerous_operation12_creation";
//            }
//        } else if (checkResult > 22 && checkResult <= 30) {
//            if (checkResult == 23) {
//                return "dangerous_operation17_creation";
//            } else if (checkResult == 24) {
//                return "dangerous_operation18_creation";
//            } else if (checkResult == 25) {
//                return "dangerous_operation19_creation";
//            } else if (checkResult == 26) {
//                return "dangerous_operation20_creation";
//            } else if (checkResult == 27 && checkResult == 30) {
//                return "dangerous_operation21_creation";
//            } else if (checkResult == 28) {
//                return "dangerous_operation22_creation";
//            } else {
//                return "dangerous_operation23_creation";
//            }
//        }
//        return null;
//    }
    private String getTemplateKey(Integer checkResult) {
        if (checkResult >= 1 && checkResult <= 8) {
            return "dangerous_operation1_creation";
        } else if (checkResult > 8 && checkResult <= 13) {
            if (checkResult > 8 && checkResult < 13) {
                return "dangerous_operation2_creation";
            } else if (checkResult == 13) {
                return "dangerous_operation3_creation";
            }
        } else if (checkResult > 13 && checkResult <= 22) {
            if (checkResult == 20) {
                return "dangerous_operation4_creation";
            } else {
                return "dangerous_operation5_creation";
            }
        } else if (checkResult > 22 && checkResult <= 30) {
            if (checkResult == 26 || checkResult == 28) {
                return "dangerous_operation6_creation";
            } else {
                return "dangerous_operation7_creation";
            }
        }
        return null;
    }


    public static String PROCESSTASK1 = "Process-task1";
    public static String PROCESSTASK2 = "Process-task2";
    public static String PROCESSTASK3 = "Process-task3";
    public static String PROCESSTASK4 = "Process-task4";

    private String getTemplateKeyByQrCode(Integer checkResult) {
        if (checkResult >= 1 && checkResult <= 8) {
            return "dangerous_operation1_1creation";
        } else if (checkResult > 8 && checkResult <= 13) {
            if (checkResult > 8 && checkResult < 13) {
                return "dangerous_operation2_2creation";
            } else if (checkResult == 13) {
                return "dangerous_operation3_3creation";
            }
        } else if (checkResult > 13 && checkResult <= 22) {
            if (checkResult == 20) {
                return "dangerous_operation4_4creation";
            } else {
                return "dangerous_operation5_5creation";
            }
        } else if (checkResult > 22 && checkResult <= 30) {
            if (checkResult == 26 || checkResult == 28) {
                return "dangerous_operation6_6creation";
            } else {
                return "dangerous_operation7_7creation";
            }
        }
        return null;
    }

    /**
     * 提交危险作业启动流程
     *
     * @param bean        危险作业
     * @param user        当前登陆人
     * @param approver    审批人
     * @param title       流程标题、名称
     * @param description 流程描述
     * @param templateKey 流程模板
     * @return
     * @throws InvalidSystemClockException
     * @throws GetHardwareIdFailedException
     */
    private Boolean startAudit(DangerousOperation bean, StaffBean user, DangerousOperationApprover approver, String
            title, String description, String templateKey) throws InvalidSystemClockException, GetHardwareIdFailedException {
        Audit audit = new Audit();
        audit.setId(DefaultIdGenerator.getInstance().generateLongId());
        if (bean.getStatus() == 1) {
            audit.setUpdateTime(bean.getUpdateTime());
            audit.setUpdateUser(bean.getUpdateUserName());
            audit.setAddUser(bean.getUpdateUserName());
            audit.setAddTime(bean.getUpdateTime());
        } else if (bean.getStatus() == 4) {
            audit.setUpdateTime(new Date());
            audit.setUpdateUser(user.getName());
            audit.setAddUser(user.getName());
            audit.setAddTime(new Date());
        }
        audit.setFlowType(1);
        audit.setOperation(1);
        audit.setTarget(DangerousOperationServiceImpl.class.getName());
        audit.setFlowName("危险作业流程待审批");
        audit.setTitle(bean.getOperationTicketTypeName() + title);
        audit.setCorpCode(bean.getCorpCode());
        audit.setInitiatorCode(user.getCode());
        audit.setDescription(description);
        audit.setState(1);
        audit.setTemplateKey(templateKey);
        // 模板组code
        audit.setSetCode("dangerous_operation");
        audit.setInitiatorAccount(user.getUserid());
        List<String> idLists = new ArrayList<>();
        idLists.add(bean.getId());
        audit.setBusinessIds(new Gson().toJson(idLists));
        // 设置流程审批节点
        Map businessMap = SetWorkFlowNode(templateKey, approver);
        return flowManagement.initFlow(user, audit, businessMap);
    }

    private Boolean startAuditByQrCode(DangerousOperation bean, StaffBean user, List<String> approverList, String
            title, String description, String templateKey) throws InvalidSystemClockException, GetHardwareIdFailedException {
        Audit audit = new Audit();
        audit.setId(DefaultIdGenerator.getInstance().generateLongId());
        if (bean.getStatus() == 1) {
            audit.setUpdateTime(bean.getUpdateTime());
            audit.setUpdateUser(bean.getUpdateUserName());
            audit.setAddUser(bean.getUpdateUserName());
            audit.setAddTime(bean.getUpdateTime());
        } else if (bean.getStatus() == 4) {
            audit.setUpdateTime(new Date());
            audit.setUpdateUser(user.getName());
            audit.setAddUser(user.getName());
            audit.setAddTime(new Date());
        }
        audit.setFlowType(1);
        audit.setOperation(1);
        audit.setTarget(DangerousOperationServiceImpl.class.getName());
        audit.setFlowName("危险作业流程待审批");
        audit.setTitle(bean.getOperationTicketTypeName() + title);
        audit.setCorpCode(bean.getCorpCode());
        audit.setInitiatorCode(user.getCode());
        audit.setDescription(description);
        audit.setState(1);
        audit.setTemplateKey(templateKey);
        // 模板组code
        audit.setSetCode("dangerous_operation");
        audit.setInitiatorAccount(user.getUserid());
        List<String> idLists = new ArrayList<>();
        idLists.add(bean.getId());
        audit.setBusinessIds(new Gson().toJson(idLists));
        Map<String, Object> businessMap = new HashMap<>();
        StringBuilder codes = new StringBuilder();
        for (String code : approverList) {
            codes.append(code.split("_")[0]).append(",");
        }
        businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
        return flowManagement.initFlow(user, audit, businessMap);
    }

    private Map SetWorkFlowNode(String templateKey, DangerousOperationApprover approver) {
        Map<String, Object> businessMap = new HashMap<>();
        if (templateKeys.get(1).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getResponsiblePerson()) ? approver.getResponsiblePerson() : "");
            businessMap.put("workPermit", StringUtils.isNotEmpty(approver.getWorkPermit()) ? approver.getWorkPermit() : "");
            businessMap.put("workGuardian", StringUtils.isNotEmpty(approver.getWorkGuardian()) ? approver.getWorkGuardian() : "");
            businessMap.put("workTicketIssuer", StringUtils.isNotEmpty(approver.getWorkTicketIssuer()) ? approver.getWorkTicketIssuer() : "");
        } else if (templateKeys.get(2).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getDeviceSpecificResponsibility()) ? approver.getDeviceSpecificResponsibility() : "");
            businessMap.put("regionalHead", StringUtils.isNotEmpty(approver.getRegionalHead()) ? approver.getRegionalHead() : "");
            businessMap.put("safetyManager", StringUtils.isNotEmpty(approver.getSafetyManager()) ? approver.getSafetyManager() : "");
            businessMap.put("factoryDirector", StringUtils.isNotEmpty(approver.getFactoryDirector()) ? approver.getFactoryDirector() : "");
        } else if (templateKeys.get(3).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getRegionalHead()) ? approver.getRegionalHead() : "");
            businessMap.put("safetyManager", StringUtils.isNotEmpty(approver.getSafetyManager()) ? approver.getSafetyManager() : "");
            businessMap.put("factoryDirector", StringUtils.isNotEmpty(approver.getFactoryDirector()) ? approver.getFactoryDirector() : "");
        } else if (templateKeys.get(4).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getBranchOffice()) ? approver.getBranchOffice() : "");
            businessMap.put("safetyManagementDepartment", StringUtils.isNotEmpty(approver.getSafetyManagementDepartment()) ? approver.getSafetyManagementDepartment() : "");
        } else if (templateKeys.get(5).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getProjectSafetyOfficer()) ? approver.getProjectSafetyOfficer() : "");
            businessMap.put("branchOffice", StringUtils.isNotEmpty(approver.getBranchOffice()) ? approver.getBranchOffice() : "");
        } else if (templateKeys.get(6).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getOperators()) ? approver.getOperators() : "");
            businessMap.put("siteSafetyExecutive", StringUtils.isNotEmpty(approver.getSiteSafetyExecutive()) ? approver.getSiteSafetyExecutive() : "");
            businessMap.put("principalPerson", StringUtils.isNotEmpty(approver.getPrincipalPerson()) ? approver.getPrincipalPerson() : "");
            businessMap.put("chairman", StringUtils.isNotEmpty(approver.getChairman()) ? approver.getChairman() : "");
        } else if (templateKeys.get(7).equals(templateKey)) {
            businessMap.put("approver", StringUtils.isNotEmpty(approver.getOperators()) ? approver.getOperators() : "");
            businessMap.put("siteSafetyExecutive", StringUtils.isNotEmpty(approver.getSiteSafetyExecutive()) ? approver.getSiteSafetyExecutive() : "");
            businessMap.put("principalPerson", StringUtils.isNotEmpty(approver.getPrincipalPerson()) ? approver.getPrincipalPerson() : "");
        }
        return businessMap;
    }

    /**
     * 编号生成 格式（例2020-08-24-001）
     *
     * @param factory 数据库连接
     * @return
     */
    @Override
    public String getCode(SessionFactory factory) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        StringBuilder sb = new StringBuilder();
        // 获取当前日期
        String date = sdf.format(new Date());
        StringBuilder builder = sb.append(date).append("-");
        // 根据当前时间查询已存在的最大code
        String maxCode = factory.getMapper(DangerousOperationMapper.class).queryMaxCode(builder.toString());
        if (null == maxCode) {
            return builder.append("001").toString();
        }
        // 截取最后三位
        String substring = maxCode.substring(maxCode.length() - 3);
        //末位加1
        long lastNum = Long.parseLong("1" + substring) + 1;
        // 替换最后三位
        maxCode = maxCode.substring(0, maxCode.length() - 3) + (lastNum + "").substring(1);
        return maxCode;
    }

    /**
     * 流程中修改危险作业
     *
     * @param bean
     * @param fileBean
     * @param user
     * @return
     */
    @Override
    public MessageBean<Integer> flowSave(DangerousOperation bean, DangerousOperationFile fileBean, StaffBean user) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        SessionFactory factory = new SessionFactory();
        try {
            Integer checkResult = check(bean.getOperationCategory(), bean.getOperationTicketType());
            if (checkResult == 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("作业分级或者作业票类型不合法");
                return msg;
            }
            Integer value = 0;
            DangerousOperation entity = factory.getMapper(DangerousOperationMapper.class).queryOne(bean.getId());
            if (null == entity) {
                msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
                return msg;
            }
            if (entity.getStatus() != 1 && entity.getStatus() != 4) {
                msg.setCode(BusinessCode.NON_DRAFT_CANNOT_EDIT.getCode());
                msg.setDescription("流程中只能修改审批的数据");
                return msg;
            }
            bean.setStatus(entity.getStatus());
            bean.setUpdateTime(entity.getUpdateTime());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            // 附件
            manageAddFile(fileBean);
            manageKeepFile(fileBean);
            List<String> keepList = fileBean.getKeepList();
            if (null != keepList && keepList.size() > 0) {
                bean.setAttachment(new Gson().toJson(keepList));
            }
            List<String> keepPreviewList = fileBean.getKeepPreviewList();
            if (null != keepPreviewList && keepPreviewList.size() > 0) {
                bean.setPreviewAttachment(new Gson().toJson(keepPreviewList));
            }
            List<String> operationApplicantList = fileBean.getOperationApplicantList();
            if (null != operationApplicantList && operationApplicantList.size() > 0) {
                bean.setOperationApplicantSignature(new Gson().toJson(operationApplicantList));
            }
            List<String> operationExecutorList = fileBean.getOperationExecutorList();
            if (null != operationExecutorList && operationExecutorList.size() > 0) {
                bean.setOperationExecutorSignature(new Gson().toJson(operationExecutorList));
            }
            List<String> hoistingCommanderList = fileBean.getHoistingCommanderList();
            if (null != hoistingCommanderList && hoistingCommanderList.size() > 0) {
                bean.setHoistingCommanderSignature(new Gson().toJson(hoistingCommanderList));
            }
            List<String> operationSupervisorList = fileBean.getOperationSupervisorList();
            if (null != operationSupervisorList && operationSupervisorList.size() > 0) {
                bean.setOperationSupervisorSignature(new Gson().toJson(operationSupervisorList));
            }
            List<String> personInChargeList = fileBean.getPersonInChargeList();
            if (null != personInChargeList && personInChargeList.size() > 0) {
                bean.setPersonInChargeSignature(new Gson().toJson(personInChargeList));
            }
            List<String> analystList = fileBean.getAnalystList();
            if (null != analystList && analystList.size() > 0) {
                bean.setAnalystSignature(new Gson().toJson(analystList));
            }
            List<String> educatedPersonList = fileBean.getEducatedPersonList();
            if (null != educatedPersonList && educatedPersonList.size() > 0) {
                bean.setEducatedPersonSignature(new Gson().toJson(educatedPersonList));
            }
            List<String> educatingPeopleList = fileBean.getEducatingPeopleList();
            if (null != educatingPeopleList && educatingPeopleList.size() > 0) {
                bean.setEducatingPeopleSignature(new Gson().toJson(educatingPeopleList));
            }
            List<String> powerSupplyPersonList = fileBean.getPowerSupplyPersonList();
            if (null != powerSupplyPersonList && powerSupplyPersonList.size() > 0) {
                bean.setPowerSupplyPersonSignature(new Gson().toJson(powerSupplyPersonList));
            }
            List<String> powerCutPersonList = fileBean.getPowerCutPersonList();
            if (null != powerCutPersonList && powerCutPersonList.size() > 0) {
                bean.setPowerCutPersonSignature(new Gson().toJson(powerCutPersonList));
            }
            List<String> completionConfirmerList = fileBean.getCompletionConfirmerList();
            if (null != completionConfirmerList && completionConfirmerList.size() > 0) {
                bean.setCompletionConfirmerSignature(new Gson().toJson(completionConfirmerList));
            }
            List<String> managementUnitHeadList = fileBean.getManagementUnitHeadList();
            if (null != managementUnitHeadList && managementUnitHeadList.size() > 0) {
                bean.setManagementUnitHeadSignature(new Gson().toJson(managementUnitHeadList));
            }
            List<String> sceneSafetyManagementList = fileBean.getSceneSafetyManagementList();
            if (null != sceneSafetyManagementList && sceneSafetyManagementList.size() > 0) {
                bean.setSceneSafetyManagementSignature(new Gson().toJson(sceneSafetyManagementList));
            }
            List<String> companyChairmanList = fileBean.getCompanyChairmanList();
            if (null != companyChairmanList && companyChairmanList.size() > 0) {
                bean.setCompanyChairmanSignature(new Gson().toJson(companyChairmanList));
            }
            value = factory.getMapper(DangerousOperationMapper.class).update(bean);
            if (value > 0) {
                value = updateRelation(bean, factory, value);
            }
            if (value > 0) {
                deleteDelFile(fileBean);
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("危险作业修改成功");
                return msg;
            } else {
                deleteKeepFile(fileBean);
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("危险作业修改失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Map> getUserCorpAndOperationCategory(StaffBean user) {
        MessageBean msgMap = new MessageBean();
        Map map = new HashMap();
        String userCorp = null;
        // 判断当前用户所属部门是否属于八大公司或集团
        if (null == corpCodeMap || corpCodeMap.isEmpty()) {
            getCorpCodeMap();
        }
        if (corpCodeMap.containsKey(user.getDepartmentCode())) {
            userCorp = user.getDepartmentCode();
        } else {
            // 不属于则找其上级，直到找到八大公司或集团为止
            MessageBean<?> msg = util.depttree(user.getDepartmentCode(), 0);
            if (msg.getCode() == 0 && null != msg.getData()) {
                DepartmentTreeBean departmentTreeBean = null;
                List<DepartmentTreeBean> data = (List<DepartmentTreeBean>) msg.getData();
                if (null != data && data.size() > 0) {
                    List<DepartmentTreeBean> collect = data.stream().filter(dept -> user.getDepartmentCode().equals(dept.getDepartmentCode())).collect(Collectors.toList());
                    if (null != collect && collect.size() > 0) {
                        departmentTreeBean = collect.get(0);
                    }
                }
                if (null != departmentTreeBean) {
                    if (orgCode.equals(departmentTreeBean.getOrgCode())) {
                        msg = util.getParentDepts(departmentTreeBean.getDepartmentCode());
                        if (msg.getData() != null) {
                            List<DepartmentTreeBean> depTreeList = (List<DepartmentTreeBean>) msg.getData();
                            ListIterator li = depTreeList.listIterator(depTreeList.size());
                            while (li.hasPrevious()) {
                                DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
                                if (corpCodeMap.containsKey(bean.getDepartmentCode())) {
                                    userCorp = bean.getDepartmentCode();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        // 判断当前公司是否为海宜公司
        if (StringUtils.isNotEmpty(userCorp)) {
            if (("50EFFB57F1A64BCB8023995D1D987709").equals(userCorp)) {
                map.put("corpCode", userCorp);
                map.put("corpName", corpCodeMap.get(userCorp));
                map.put("operationCategory", 0);
                map.put("operationCategoryName", "海宜公司模板");
                map.put("show", false);
            } else if (("82D03410EB00475E919231DF9ADBDE14").equals(userCorp)) {
                map.put("corpCode", userCorp);
                map.put("corpName", corpCodeMap.get(userCorp));
                map.put("operationCategory", 3);
                map.put("operationCategoryName", "供水公司模板");
                map.put("show", false);
            } else if (("2B59A706DCB3403F9D0EF38DC5F53DA3").equals(userCorp) || ("7AF8AD90D906464BB83BB7577A109005").equals(userCorp)) {
                // 机司和管网，使用模板二
                map.put("corpCode", userCorp);
                map.put("corpName", corpCodeMap.get(userCorp));
                map.put("operationCategory", 2);
                map.put("operationCategoryName", "模板二");
                map.put("show", false);
            } else if (("776B361BFFAC4F00BBF459CD1303A8B2").equals(userCorp)) {
                map.put("corpCode", userCorp);
                map.put("corpName", corpCodeMap.get(userCorp));
                map.put("show", true);
            } else {
                // 排水，物业，物流默认使用模拟板一
                map.put("corpCode", userCorp);
                map.put("corpName", corpCodeMap.get(userCorp));
                map.put("operationCategory", 1);
                map.put("operationCategoryName", "模板一");
                map.put("show", false);
            }
        }
        msgMap.setCode(BusinessCode.SUCCESS.getCode());
        msgMap.setDescription(BusinessCode.SUCCESS.getDescription());
        msgMap.setData(map);
        return msgMap;
    }

    @Override
    public MessageBean<List<StaffBean>> getStaffByCertificate(SessionFactory factory, String corpCode, String certificateTypeName) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        try {
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            // 获取公司下的有对应的人员执照信息
            List<MyCertificate> staffBeanList = mapper.getCertificate(corpCode, certificateTypeName);
            //获取人员信息
            List<StaffBean> beanList = new ArrayList<>();
            if (null != staffBeanList && staffBeanList.size() > 0) {
                List<String> userCodeList = staffBeanList.stream().map(myCertificate -> myCertificate.getStaffCode()).collect(Collectors.toList());
                beanList = mapper.getStaff(userCodeList);
            }
            msg.setData(beanList);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public List<DangerousOperationVo> exportList(String corpCode, String operationTicketType, String operationCode, Integer status, String startTime, String endTime) {
        try (SessionFactory factory = new SessionFactory()) {
            String codes = util.getCodes(corpCode);
            List<DangerousOperation> dangerousOperationList = factory.getMapper(DangerousOperationMapper.class).queryByCondition(codes, null, operationTicketType, null, null, operationCode, status, startTime, endTime, null, null, null);
            List<DangerousOperationVo> list = dangerousOperationList.stream().map(bean -> {
                DangerousOperationVo vo = new DangerousOperationVo();
                BeanUtils.copyProperties(bean, vo);
                return vo;
            }).collect(Collectors.toList());
            list.forEach(bean -> getName(bean));
            factory.close();
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<DataBean<DangerousOperation>> homePageOperationList(String corpCode, String operationCategory, String operationTicketType, String operationCategoryName, String operationTicketTypeName, String operationCode, Integer status, String startTime, String endTime, Integer start, Integer rows) {
        MessageBean<DataBean<DangerousOperation>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            rows = (rows == null || rows <= 0) ? 1 : rows;
            String deptCodes = util.getDeptCodes(corpCode);
            List<DangerousOperation> list = factory.getMapper(DangerousOperationMapper.class).homePageOperationList(deptCodes, operationCategory, operationTicketType, operationCategoryName, operationTicketTypeName, operationCode, status, startTime, endTime, start, rows);
            Integer totalNumber = factory.getMapper(DangerousOperationMapper.class).homePageOperationCount(deptCodes, operationCategory, operationTicketType, operationCategoryName, operationTicketTypeName, operationCode, status, startTime, endTime);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<DangerousOperation> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("首页工作台危险作业列表查询成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }

    }

    @Override
    public MessageBean<Integer> flowSignSave(SessionFactory factory, StaffBean user, String id, MultipartFile[] files) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "签名提交成功", Integer.class);
        try {
            DangerousOperationMapper mapper = factory.getMapper(DangerousOperationMapper.class);
            // 获取作业票详情
            DangerousOperation dangerousOperation = mapper.detail(id);
            //获取流程数据
            // 根据业务id和更新时间来获取审批Audit数据
            List<String> idLists = new ArrayList<>();
            idLists.add(id);
            Audit audit = auditService.queryByBusinessIds(new Gson().toJson(idLists), dangerousOperation.getUpdateTime());
            // 获取流程审批历史轨迹
            MessageBean<?> history = flowService.history(audit.getSetCode(), audit.getTemplateKey(), audit.getId());
            Integer checkResult = check(dangerousOperation.getOperationCategory(), dangerousOperation.getOperationTicketType());
            String templateKey = getTemplateKey(checkResult);
            if (0 == history.getCode() && history.getData() != null) {
                List<Map> historys = (List<Map>) history.getData();
                if (historys != null && historys.size() > 0) {
                    List<String> signList = new ArrayList<>();
                    if (null != files && files.length > 0) {
                        for (MultipartFile file : files) {
                            String url = clientWrapper.uploadFile(file);
                            //获得文件名
                            String fileName = file.getOriginalFilename();
                            signList.add(url + "#" + fileName);
                        }
                    }
                    Map map = historys.get(historys.size() - 1);
                    String nowNodeCode = map.get("nowNodeCode").toString();
                    if ("dangerous_operation1_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getPersonInChargeSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getPersonInChargeSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setPersonInChargeSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getOperationSupervisorSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getOperationSupervisorSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setOperationSupervisorSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK3.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getLicensorSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getLicensorSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setLicensorSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK4.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getSignerSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getSignerSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setSignerSignature(new Gson().toJson(signList));
                        }
                    } else if ("dangerous_operation2_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getDeviceSpecificResponsibilitySignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getDeviceSpecificResponsibilitySignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setDeviceSpecificResponsibilitySignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getRegionalHeadSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getRegionalHeadSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setRegionalHeadSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK3.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getSceneSafetyManagementSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getSceneSafetyManagementSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setSceneSafetyManagementSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK4.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getFactoryDirectorSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getFactoryDirectorSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setFactoryDirectorSignature(new Gson().toJson(signList));
                        }
                    } else if ("dangerous_operation3_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getRegionalHeadSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getRegionalHeadSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setRegionalHeadSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getSceneSafetyManagementSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getSceneSafetyManagementSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setSceneSafetyManagementSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK3.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getFactoryDirectorSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getFactoryDirectorSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setFactoryDirectorSignature(new Gson().toJson(signList));
                        }
                    } else if ("dangerous_operation4_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getBranchOfficeSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getBranchOfficeSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setBranchOfficeSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getSafetyManagementDepartmentSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getSafetyManagementDepartmentSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setSafetyManagementDepartmentSignature(new Gson().toJson(signList));
                        }
                    } else if ("dangerous_operation5_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getProjectSafetyOfficerSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getProjectSafetyOfficerSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setProjectSafetyOfficerSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getBranchOfficeSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getBranchOfficeSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setBranchOfficeSignature(new Gson().toJson(signList));
                        }
                    } else if ("dangerous_operation6_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getOperationExecutorSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getOperationExecutorSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setOperationExecutorSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getSceneSafetyManagementSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getSceneSafetyManagementSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setSceneSafetyManagementSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK3.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getManagementUnitHeadSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getManagementUnitHeadSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setManagementUnitHeadSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK4.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getCompanyChairmanSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getCompanyChairmanSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setCompanyChairmanSignature(new Gson().toJson(signList));
                        }
                    } else if ("dangerous_operation7_creation".equals(templateKey)) {
                        if (PROCESSTASK1.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getOperationExecutorSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getOperationExecutorSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setOperationExecutorSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK2.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getSceneSafetyManagementSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getSceneSafetyManagementSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setSceneSafetyManagementSignature(new Gson().toJson(signList));
                        } else if (PROCESSTASK3.equals(nowNodeCode)) {
                            if (StringUtils.isNotEmpty(dangerousOperation.getManagementUnitHeadSignature())) {
                                List<String> array = JSONObject.parseArray(dangerousOperation.getManagementUnitHeadSignature(), String.class);
                                signList.addAll(array);
                            }
                            dangerousOperation.setManagementUnitHeadSignature(new Gson().toJson(signList));
                        }
                    }
                }
            }
            Integer integer = mapper.updateFlowSign(dangerousOperation);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }


    private void getName(DangerousOperationVo bean) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != bean) {
            if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                        ? null : map.get(bean.getCorpCode()));
            }
            if (null != bean.getOperationStartTime()) {
                bean.setOperationStartTimeStr(sdf.format(bean.getOperationStartTime()));
            }
            if (null != bean.getOperationEndTime()) {
                bean.setOperationEndTimeStr(sdf.format(bean.getOperationEndTime()));
            }
        }
    }

    /**
     * 获取八大公司与集团信息
     */
    public void getCorpCodeMap() {
        // 获取公司信息
        MessageBean<List<DictType>> dictMsg = dictTypeService.getDictTypesAndDictDatas("公司");
        if (null != dictMsg.getData()) {
            List<DictType> dictData = dictMsg.getData();
            if (null != dictData && dictData.size() > 0) {
                List<DictData> dataList = dictData.get(0).getDataList();
                dataList.stream().forEach(dict -> corpCodeMap.put(dict.getDictValue(), dict.getDictLabel()));
            }
        }
    }


    /**
     * 处理新增附件信息
     *
     * @param fileBean
     * @throws IOException
     */
    public void manageAddFile(DangerousOperationFile fileBean) throws IOException {
        // 附件
        MultipartFile[] files = fileBean.getFiles();
        if (null != files && files.length > 0) {
            for (MultipartFile file : files) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getKeepList().add(url + "#" + fileName);
                File previewFile = docConverterUtils.converter(file);
                if (previewFile != null) {
                    String previewFilePath = clientWrapper.uploadFile(new FileInputStream(previewFile), previewFile.length(), FilenameUtils.getExtension(previewFile.getName()));
                    fileBean.getKeepPreviewList().add(previewFilePath);
                } else {
                    fileBean.getKeepPreviewList().add(null);
                }
            }
        }
        // 作业申请人签字附件
        MultipartFile[] applicantFiles = fileBean.getOperationApplicantFile();
        if (null != applicantFiles && applicantFiles.length > 0) {
            for (MultipartFile file : applicantFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getOperationApplicantList().add(url + "#" + fileName);
            }
        }
        //作业执行人签字附件
        MultipartFile[] operationExecutorFiles = fileBean.getOperationExecutorFile();
        if (null != operationExecutorFiles && operationExecutorFiles.length > 0) {
            for (MultipartFile file : operationExecutorFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getOperationExecutorList().add(url + "#" + fileName);
            }
        }
        //作业指挥人签字附件
        MultipartFile[] hoistingCommanderFiles = fileBean.getHoistingCommanderFile();
        if (null != hoistingCommanderFiles && hoistingCommanderFiles.length > 0) {
            for (MultipartFile file : hoistingCommanderFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getHoistingCommanderList().add(url + "#" + fileName);
            }
        }
        //作业监护人签字附件
        MultipartFile[] supervisorFiles = fileBean.getOperationSupervisorFile();
        if (null != supervisorFiles && supervisorFiles.length > 0) {
            for (MultipartFile file : supervisorFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getOperationSupervisorList().add(url + "#" + fileName);
            }
        }
        //作业负责人签字附件
        MultipartFile[] personInChargeFiles = fileBean.getPersonInChargeFile();
        if (null != personInChargeFiles && personInChargeFiles.length > 0) {
            for (MultipartFile file : personInChargeFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getPersonInChargeList().add(url + "#" + fileName);
            }
        }
        //分析人签字附件
        MultipartFile[] analystFiles = fileBean.getAnalystFile();
        if (null != analystFiles && analystFiles.length > 0) {
            for (MultipartFile file : analystFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getAnalystList().add(url + "#" + fileName);
            }
        }
        //受教育人签字附件
        MultipartFile[] educatedPersonFiles = fileBean.getEducatedPersonFile();
        if (null != educatedPersonFiles && educatedPersonFiles.length > 0) {
            for (MultipartFile file : educatedPersonFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getEducatedPersonList().add(url + "#" + fileName);
            }
        }
        //教育人签字附件
        MultipartFile[] educatingPeopleFiles = fileBean.getEducatingPeopleFile();
        if (null != educatingPeopleFiles && educatingPeopleFiles.length > 0) {
            for (MultipartFile file : educatingPeopleFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getEducatingPeopleList().add(url + "#" + fileName);
            }
        }
        //送电人签字附件
        MultipartFile[] supplyPersonFiles = fileBean.getPowerSupplyPersonFile();
        if (null != supplyPersonFiles && supplyPersonFiles.length > 0) {
            for (MultipartFile file : supplyPersonFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getPowerSupplyPersonList().add(url + "#" + fileName);
            }
        }
        //停电人签字附件
        MultipartFile[] cutPersonFiles = fileBean.getPowerCutPersonFile();
        if (null != cutPersonFiles && cutPersonFiles.length > 0) {
            for (MultipartFile file : cutPersonFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getPowerCutPersonList().add(url + "#" + fileName);
            }
        }
        //完工确认人签字附件
        MultipartFile[] confirmerFiles = fileBean.getCompletionConfirmerFile();
        if (null != confirmerFiles && confirmerFiles.length > 0) {
            for (MultipartFile file : confirmerFiles) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getCompletionConfirmerList().add(url + "#" + fileName);
            }
        }
        //管理单位负责人人签字附件
        MultipartFile[] managementUnitHeadFile = fileBean.getManagementUnitHeadFile();
        if (null != managementUnitHeadFile && managementUnitHeadFile.length > 0) {
            for (MultipartFile file : managementUnitHeadFile) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getManagementUnitHeadList().add(url + "#" + fileName);
            }
        }
        //安全管理人员签名附件
        MultipartFile[] sceneSafetyManagementFile = fileBean.getSceneSafetyManagementFile();
        if (null != sceneSafetyManagementFile && sceneSafetyManagementFile.length > 0) {
            for (MultipartFile file : sceneSafetyManagementFile) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getSceneSafetyManagementList().add(url + "#" + fileName);
            }
        }
        //公司董事长签名附件
        MultipartFile[] companyChairmanFile = fileBean.getCompanyChairmanFile();
        if (null != companyChairmanFile && companyChairmanFile.length > 0) {
            for (MultipartFile file : companyChairmanFile) {
                String url = clientWrapper.uploadFile(file);
                //获得文件名
                String fileName = file.getOriginalFilename();
                fileBean.getCompanyChairmanList().add(url + "#" + fileName);
            }
        }
    }

    /**
     * 处理保留的附件信息
     *
     * @param fileBean
     */
    private void manageKeepFile(DangerousOperationFile fileBean) {
        // 保留的附件地址
        String keepFiles = fileBean.getKeepFiles();
        if (StringUtils.isNotEmpty(keepFiles)) {
            String[] keepArray = keepFiles.split("[,，]");
            fileBean.getKeepList().addAll(Arrays.asList(keepArray));
        }
        // 保留的附件预览地址
        String keepPreviewFiles = fileBean.getKeepPreviewFiles();
        if (StringUtils.isNotEmpty(keepPreviewFiles)) {
            String[] keepPreview = keepPreviewFiles.split("[,，]");
            fileBean.getKeepPreviewList().addAll(Arrays.asList(keepPreview));
        }
        //保留的作业申请人签字附件地址
        String keepApplicantFiles = fileBean.getOperationApplicantFileKeep();
        if (StringUtils.isNotEmpty(keepApplicantFiles)) {
            String[] keepArray = keepApplicantFiles.split("[,，]");
            fileBean.getOperationApplicantList().addAll(Arrays.asList(keepArray));
        }
        //保留的作业执行人签字附件地址
        String keepExecutorFiles = fileBean.getOperationExecutorFileKeep();
        if (StringUtils.isNotEmpty(keepExecutorFiles)) {
            String[] keepArray = keepExecutorFiles.split("[,，]");
            fileBean.getOperationExecutorList().addAll(Arrays.asList(keepArray));
        }
        //保留的作业指挥人签字附件地址
        String keepHoistingCommanderFiles = fileBean.getHoistingCommanderFileKeep();
        if (StringUtils.isNotEmpty(keepHoistingCommanderFiles)) {
            String[] keepArray = keepHoistingCommanderFiles.split("[,，]");
            fileBean.getHoistingCommanderList().addAll(Arrays.asList(keepArray));
        }
        //保留的作业监护人签字附件地址
        String keepOperationSupervisorFiles = fileBean.getOperationSupervisorFileKeep();
        if (StringUtils.isNotEmpty(keepOperationSupervisorFiles)) {
            String[] keepArray = keepOperationSupervisorFiles.split("[,，]");
            fileBean.getOperationSupervisorList().addAll(Arrays.asList(keepArray));
        }
        //保留的作业负责人签字附件地址
        String keepPersonInChargeFiles = fileBean.getPersonInChargeFileKeep();
        if (StringUtils.isNotEmpty(keepPersonInChargeFiles)) {
            String[] keepArray = keepPersonInChargeFiles.split("[,，]");
            fileBean.getPersonInChargeList().addAll(Arrays.asList(keepArray));
        }
        //保留的分析人签字附件地址
        String keepAnalystFiles = fileBean.getAnalystFileKeep();
        if (StringUtils.isNotEmpty(keepAnalystFiles)) {
            String[] keepArray = keepAnalystFiles.split("[,，]");
            fileBean.getAnalystList().addAll(Arrays.asList(keepArray));
        }
        //保留的受教育人签字附件地址
        String keepEducatedPersonFiles = fileBean.getEducatedPersonFileKeep();
        if (StringUtils.isNotEmpty(keepEducatedPersonFiles)) {
            String[] keepArray = keepEducatedPersonFiles.split("[,，]");
            fileBean.getEducatedPersonList().addAll(Arrays.asList(keepArray));
        }
        //保留的教育人签字附件地址
        String keepEducatingPeopleFiles = fileBean.getEducatingPeopleFileKeep();
        if (StringUtils.isNotEmpty(keepEducatingPeopleFiles)) {
            String[] keepArray = keepEducatingPeopleFiles.split("[,，]");
            fileBean.getEducatingPeopleList().addAll(Arrays.asList(keepArray));
        }
        //保留的送电人签字附件地址
        String keepPowerSupplyPersonFiles = fileBean.getPowerSupplyPersonFileKeep();
        if (StringUtils.isNotEmpty(keepPowerSupplyPersonFiles)) {
            String[] keepArray = keepPowerSupplyPersonFiles.split("[,，]");
            fileBean.getPowerSupplyPersonList().addAll(Arrays.asList(keepArray));
        }
        //保留的停电人签字附件地址
        String keepPowerCutPersonFiles = fileBean.getPowerCutPersonFileKeep();
        if (StringUtils.isNotEmpty(keepPowerCutPersonFiles)) {
            String[] keepArray = keepPowerCutPersonFiles.split("[,，]");
            fileBean.getPowerCutPersonList().addAll(Arrays.asList(keepArray));
        }
        //保留的完工确认人签字附件地址
        String keepCompletionConfirmerFiles = fileBean.getCompletionConfirmerFileKeep();
        if (StringUtils.isNotEmpty(keepCompletionConfirmerFiles)) {
            String[] keepArray = keepCompletionConfirmerFiles.split("[,，]");
            fileBean.getCompletionConfirmerList().addAll(Arrays.asList(keepArray));
        }
        //保留的管理单位负责人签字附件地址
        String managementUnitHeadFileKeep = fileBean.getManagementUnitHeadFileKeep();
        if (StringUtils.isNotEmpty(managementUnitHeadFileKeep)) {
            String[] keepArray = managementUnitHeadFileKeep.split("[,，]");
            fileBean.getManagementUnitHeadList().addAll(Arrays.asList(keepArray));
        }
        //保留的安全管理人员签名附件
        String sceneSafetyManagementFileKeep = fileBean.getSceneSafetyManagementFileKeep();
        if (StringUtils.isNotEmpty(sceneSafetyManagementFileKeep)) {
            String[] keepArray = sceneSafetyManagementFileKeep.split("[,，]");
            fileBean.getSceneSafetyManagementList().addAll(Arrays.asList(keepArray));
        }
        //保留的公司董事长签名附件
        String companyChairmanFileKeep = fileBean.getCompanyChairmanFileKeep();
        if (StringUtils.isNotEmpty(companyChairmanFileKeep)) {
            String[] keepArray = companyChairmanFileKeep.split("[,，]");
            fileBean.getCompanyChairmanList().addAll(Arrays.asList(keepArray));
        }
    }


    /**
     * 新增危险作业
     *
     * @param bean
     * @param fileBean
     * @param msg
     * @param factory
     * @param checkResult
     * @param user
     * @param approver
     * @return
     * @throws Exception
     */
    public MessageBean<Integer> addOperation(DangerousOperation bean, DangerousOperationFile fileBean, MessageBean<Integer> msg, SessionFactory factory, Integer checkResult, StaffBean user, DangerousOperationApprover approver) throws Exception {
        // 获取编码
        String code = getCode(factory);
        bean.setOperationCode(code);
        bean.setId(DefaultIdGenerator.getInstance().generateLongId());
        bean.setAddTime(bean.getUpdateTime());
        bean.setAddUser(bean.getUpdateUser());
        bean.setAddUserName(bean.getUpdateUserName());
        List<String> keepList = fileBean.getKeepList();
        if (null != keepList && keepList.size() > 0) {
            bean.setAttachment(new Gson().toJson(keepList));
        }
        List<String> keepPreviewList = fileBean.getKeepPreviewList();
        if (null != keepPreviewList && keepPreviewList.size() > 0) {
            bean.setPreviewAttachment(new Gson().toJson(keepPreviewList));
        }
        List<String> operationApplicantList = fileBean.getOperationApplicantList();
        if (null != operationApplicantList && operationApplicantList.size() > 0) {
            bean.setOperationApplicantSignature(new Gson().toJson(operationApplicantList));
        }
        List<String> operationExecutorList = fileBean.getOperationExecutorList();
        if (null != operationExecutorList && operationExecutorList.size() > 0) {
            bean.setOperationExecutorSignature(new Gson().toJson(operationExecutorList));
        }
        List<String> hoistingCommanderList = fileBean.getHoistingCommanderList();
        if (null != hoistingCommanderList && hoistingCommanderList.size() > 0) {
            bean.setHoistingCommanderSignature(new Gson().toJson(hoistingCommanderList));
        }
        List<String> operationSupervisorList = fileBean.getOperationSupervisorList();
        if (null != operationSupervisorList && operationSupervisorList.size() > 0) {
            bean.setOperationSupervisorSignature(new Gson().toJson(operationSupervisorList));
        }
        List<String> personInChargeList = fileBean.getPersonInChargeList();
        if (null != personInChargeList && personInChargeList.size() > 0) {
            bean.setPersonInChargeSignature(new Gson().toJson(personInChargeList));
        }
        List<String> analystList = fileBean.getAnalystList();
        if (null != analystList && analystList.size() > 0) {
            bean.setAnalystSignature(new Gson().toJson(analystList));
        }
        List<String> educatedPersonList = fileBean.getEducatedPersonList();
        if (null != educatedPersonList && educatedPersonList.size() > 0) {
            bean.setEducatedPersonSignature(new Gson().toJson(educatedPersonList));
        }
        List<String> educatingPeopleList = fileBean.getEducatingPeopleList();
        if (null != educatingPeopleList && educatingPeopleList.size() > 0) {
            bean.setEducatingPeopleSignature(new Gson().toJson(educatingPeopleList));
        }
        List<String> powerSupplyPersonList = fileBean.getPowerSupplyPersonList();
        if (null != powerSupplyPersonList && powerSupplyPersonList.size() > 0) {
            bean.setPowerSupplyPersonSignature(new Gson().toJson(powerSupplyPersonList));
        }
        List<String> powerCutPersonList = fileBean.getPowerCutPersonList();
        if (null != powerCutPersonList && powerCutPersonList.size() > 0) {
            bean.setPowerCutPersonSignature(new Gson().toJson(powerCutPersonList));
        }
        List<String> completionConfirmerList = fileBean.getCompletionConfirmerList();
        if (null != completionConfirmerList && completionConfirmerList.size() > 0) {
            bean.setCompletionConfirmerSignature(new Gson().toJson(completionConfirmerList));
        }
        List<String> managementUnitHeadList = fileBean.getManagementUnitHeadList();
        if (null != managementUnitHeadList && managementUnitHeadList.size() > 0) {
            bean.setManagementUnitHeadSignature(new Gson().toJson(managementUnitHeadList));
        }
        List<String> sceneSafetyManagementList = fileBean.getSceneSafetyManagementList();
        if (null != sceneSafetyManagementList && sceneSafetyManagementList.size() > 0) {
            bean.setSceneSafetyManagementSignature(new Gson().toJson(sceneSafetyManagementList));
        }
        List<String> companyChairmanList = fileBean.getCompanyChairmanList();
        if (null != companyChairmanList && companyChairmanList.size() > 0) {
            bean.setCompanyChairmanSignature(new Gson().toJson(companyChairmanList));
        }
        String templateKey = null;
        Boolean flag = false;
        if (bean.getExternalWork() == 0 && bean.getStatus() == 1) {
            templateKey = getTemplateKey(checkResult);
            // 启动流程
            if (null == templateKey) {
                factory.close();
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("未找到流程模板");
                return msg;
            }
            if (bean.getOperationCategory() == 3) {
                // 检查审批是否选择或者是否有签名
                Boolean checkApprover = checkApprover(templateKey, bean, approver);
                if (checkApprover) {
                    if (ObjectUtil.checkObjAllFieldsIsNull(approver)) {
                        bean.setStatus(2);
                    } else {
                        flag = true;
                    }
                } else {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("请完成签名或者选择审批人后提交");
                    factory.close(false);
                    return msg;
                }
            } else {
                flag = true;
            }
        }
        Integer value = factory.getMapper(DangerousOperationMapper.class).insert(bean);
        if (value > 0) {
            value = insertRelation(bean, factory, value);
        }
        if (value > 0) {
            if (flag) {
                Boolean startAudit = startAudit(bean, user, approver, "流程待审批", "危险作业流程", templateKey);
                if (!startAudit) {
                    deleteKeepFile(fileBean);
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("危险作业流程启动失败");
                    return msg;
                } else {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("危险作业提交成功");
                    msg.setData(value);
                    return msg;
                }
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("危险作业保存成功");
            return msg;
        } else {
            deleteKeepFile(fileBean);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    /**
     * 检查是否选择审批人，以及签字情况
     *
     * @param templateKey
     * @param bean
     * @param approver
     * @return false：未选审批人，并且对应的签字也没有签
     */
    private Boolean checkApprover(String templateKey, DangerousOperation bean, DangerousOperationApprover approver) {
        if (ObjectUtil.checkObjAllFieldsIsNull(approver)) {
            if (templateKeys.get(6).equals(templateKey)) {
                if (StringUtils.isEmpty(bean.getOperationExecutorSignature())
                        || StringUtils.isEmpty(bean.getSceneSafetyManagementSignature())
                        || StringUtils.isEmpty(bean.getManagementUnitHeadSignature())
                        || StringUtils.isEmpty(bean.getCompanyChairmanSignature())) {
                    return false;
                }
            } else if (templateKeys.get(7).equals(templateKey)) {
                if (StringUtils.isEmpty(bean.getOperationExecutorSignature())
                        || StringUtils.isEmpty(bean.getSceneSafetyManagementSignature())
                        || StringUtils.isEmpty(bean.getManagementUnitHeadSignature())) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 操作失败，删除上传的附件
     *
     * @param fileBean
     */

    public void deleteKeepFile(DangerousOperationFile fileBean) {
        // 附件
        List<String> keepList = fileBean.getKeepList();
        if (null != keepList && keepList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getKeepFiles())) {
                List<String> keeps = Arrays.asList(fileBean.getKeepFiles().split("[,，]"));
                for (String url : keepList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : keepList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 附件预览
        List<String> keepPreviewList = fileBean.getKeepPreviewList();
        if (null != keepPreviewList && keepPreviewList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getKeepPreviewFiles())) {
                List<String> keeps = Arrays.asList(fileBean.getKeepPreviewFiles().split("[,，]"));
                for (String url : keepPreviewList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : keepPreviewList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 作业申请人签字附件
        List<String> operationApplicantList = fileBean.getOperationApplicantList();
        if (null != operationApplicantList && operationApplicantList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getOperationApplicantFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getOperationApplicantFileKeep().split("[,，]"));
                for (String url : operationApplicantList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : operationApplicantList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 作业执行人签字附件
        List<String> operationExecutorList = fileBean.getOperationExecutorList();
        if (null != operationExecutorList && operationExecutorList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getOperationExecutorFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getOperationExecutorFileKeep().split("[,，]"));
                for (String url : operationExecutorList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : operationExecutorList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 作业指挥人签字附件
        List<String> hoistingCommanderList = fileBean.getHoistingCommanderList();
        if (null != hoistingCommanderList && hoistingCommanderList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getHoistingCommanderFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getHoistingCommanderFileKeep().split("[,，]"));
                for (String url : hoistingCommanderList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : hoistingCommanderList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 作业监护人签字附件
        List<String> operationSupervisorList = fileBean.getOperationSupervisorList();
        if (null != operationSupervisorList && operationSupervisorList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getOperationSupervisorFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getOperationSupervisorFileKeep().split("[,，]"));
                for (String url : operationSupervisorList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : operationSupervisorList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 作业负责人签字附件
        List<String> personInChargeList = fileBean.getPersonInChargeList();
        if (null != personInChargeList && personInChargeList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getPersonInChargeFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getPersonInChargeFileKeep().split("[,，]"));
                for (String url : personInChargeList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : personInChargeList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 分析人签字附件
        List<String> analystList = fileBean.getAnalystList();
        if (null != analystList && analystList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getAnalystFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getAnalystFileKeep().split("[,，]"));
                for (String url : analystList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : analystList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 受教育人签字附件
        List<String> educatedPersonList = fileBean.getEducatedPersonList();
        if (null != educatedPersonList && educatedPersonList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getEducatedPersonFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getEducatedPersonFileKeep().split("[,，]"));
                for (String url : educatedPersonList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : educatedPersonList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 教育人签字附件
        List<String> educatingPeopleList = fileBean.getEducatingPeopleList();
        if (null != educatingPeopleList && educatingPeopleList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getEducatingPeopleFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getEducatingPeopleFileKeep().split("[,，]"));
                for (String url : educatingPeopleList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : educatingPeopleList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 送电人签字附件
        List<String> powerSupplyPersonList = fileBean.getPowerSupplyPersonList();
        if (null != powerSupplyPersonList && powerSupplyPersonList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getPowerSupplyPersonFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getPowerSupplyPersonFileKeep().split("[,，]"));
                for (String url : powerSupplyPersonList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : powerSupplyPersonList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 停电人签字附件
        List<String> powerCutPersonList = fileBean.getPowerCutPersonList();
        if (null != powerCutPersonList && powerCutPersonList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getPowerCutPersonFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getPowerCutPersonFileKeep().split("[,，]"));
                for (String url : powerCutPersonList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : powerCutPersonList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 完工确认人签字附件
        List<String> completionConfirmerList = fileBean.getCompletionConfirmerList();
        if (null != completionConfirmerList && completionConfirmerList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getCompletionConfirmerFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getCompletionConfirmerFileKeep().split("[,，]"));
                for (String url : completionConfirmerList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : completionConfirmerList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 管理单位负责人签字附件
        List<String> managementUnitHeadList = fileBean.getManagementUnitHeadList();
        if (null != managementUnitHeadList && managementUnitHeadList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getManagementUnitHeadFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getManagementUnitHeadFileKeep().split("[,，]"));
                for (String url : managementUnitHeadList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : managementUnitHeadList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 安全管理人员签名附件
        List<String> sceneSafetyManagementList = fileBean.getSceneSafetyManagementList();
        if (null != sceneSafetyManagementList && sceneSafetyManagementList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getSceneSafetyManagementFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getSceneSafetyManagementFileKeep().split("[,，]"));
                for (String url : sceneSafetyManagementList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : sceneSafetyManagementList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
        // 公司董事长签名附件
        List<String> companyChairmanList = fileBean.getCompanyChairmanList();
        if (null != companyChairmanList && companyChairmanList.size() > 0) {
            if (StringUtils.isNotEmpty(fileBean.getCompanyChairmanFileKeep())) {
                List<String> keeps = Arrays.asList(fileBean.getCompanyChairmanFileKeep().split("[,，]"));
                for (String url : companyChairmanList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : companyChairmanList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
    }


    /**
     * 危险作业修改
     *
     * @param bean
     * @param fileBean
     * @param msg
     * @param factory
     * @param checkResult
     * @param user
     * @param approver
     * @return
     * @throws Exception
     */
    public MessageBean<Integer> updateOperation(DangerousOperation bean, DangerousOperationFile fileBean, MessageBean<Integer> msg, SessionFactory factory, Integer checkResult, StaffBean user, DangerousOperationApprover approver) throws Exception {
        DangerousOperation entity = factory.getMapper(DangerousOperationMapper.class).queryOne(bean.getId());
        if (null == entity) {
            factory.close();
            msg.setCode(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getCode());
            msg.setDescription(BusinessCode.DANGEROUS_OPERATION_NOT_EXIST.getDescription());
            return msg;
        }
        if (entity.getStatus() != 0) {
            factory.close();
            msg.setCode(BusinessCode.NON_DRAFT_CANNOT_EDIT.getCode());
            msg.setDescription("非草稿状态不能编辑");
            return msg;
        }
        // 要保留的附件管理
        manageKeepFile(fileBean);
        List<String> keepList = fileBean.getKeepList();
        if (null != keepList && keepList.size() > 0) {
            bean.setAttachment(new Gson().toJson(keepList));
        }
        List<String> keepPreviewList = fileBean.getKeepPreviewList();
        if (null != keepPreviewList && keepPreviewList.size() > 0) {
            bean.setPreviewAttachment(new Gson().toJson(keepPreviewList));
        }
        List<String> operationApplicantList = fileBean.getOperationApplicantList();
        if (null != operationApplicantList && operationApplicantList.size() > 0) {
            bean.setOperationApplicantSignature(new Gson().toJson(operationApplicantList));
        }
        List<String> operationExecutorList = fileBean.getOperationExecutorList();
        if (null != operationExecutorList && operationExecutorList.size() > 0) {
            bean.setOperationExecutorSignature(new Gson().toJson(operationExecutorList));
        }
        List<String> hoistingCommanderList = fileBean.getHoistingCommanderList();
        if (null != hoistingCommanderList && hoistingCommanderList.size() > 0) {
            bean.setHoistingCommanderSignature(new Gson().toJson(hoistingCommanderList));
        }
        List<String> operationSupervisorList = fileBean.getOperationSupervisorList();
        if (null != operationSupervisorList && operationSupervisorList.size() > 0) {
            bean.setOperationSupervisorSignature(new Gson().toJson(operationSupervisorList));
        }
        List<String> personInChargeList = fileBean.getPersonInChargeList();
        if (null != personInChargeList && personInChargeList.size() > 0) {
            bean.setPersonInChargeSignature(new Gson().toJson(personInChargeList));
        }
        List<String> analystList = fileBean.getAnalystList();
        if (null != analystList && analystList.size() > 0) {
            bean.setAnalystSignature(new Gson().toJson(analystList));
        }
        List<String> educatedPersonList = fileBean.getEducatedPersonList();
        if (null != educatedPersonList && educatedPersonList.size() > 0) {
            bean.setEducatedPersonSignature(new Gson().toJson(educatedPersonList));
        }
        List<String> educatingPeopleList = fileBean.getEducatingPeopleList();
        if (null != educatingPeopleList && educatingPeopleList.size() > 0) {
            bean.setEducatingPeopleSignature(new Gson().toJson(educatingPeopleList));
        }
        List<String> powerSupplyPersonList = fileBean.getPowerSupplyPersonList();
        if (null != powerSupplyPersonList && powerSupplyPersonList.size() > 0) {
            bean.setPowerSupplyPersonSignature(new Gson().toJson(powerSupplyPersonList));
        }
        List<String> powerCutPersonList = fileBean.getPowerCutPersonList();
        if (null != powerCutPersonList && powerCutPersonList.size() > 0) {
            bean.setPowerCutPersonSignature(new Gson().toJson(powerCutPersonList));
        }
        List<String> completionConfirmerList = fileBean.getCompletionConfirmerList();
        if (null != completionConfirmerList && completionConfirmerList.size() > 0) {
            bean.setCompletionConfirmerSignature(new Gson().toJson(completionConfirmerList));
        }
        List<String> managementUnitHeadList = fileBean.getManagementUnitHeadList();
        if (null != managementUnitHeadList && managementUnitHeadList.size() > 0) {
            bean.setManagementUnitHeadSignature(new Gson().toJson(managementUnitHeadList));
        }
        List<String> sceneSafetyManagementList = fileBean.getSceneSafetyManagementList();
        if (null != sceneSafetyManagementList && sceneSafetyManagementList.size() > 0) {
            bean.setSceneSafetyManagementSignature(new Gson().toJson(sceneSafetyManagementList));
        }
        List<String> companyChairmanList = fileBean.getCompanyChairmanList();
        if (null != companyChairmanList && companyChairmanList.size() > 0) {
            bean.setCompanyChairmanSignature(new Gson().toJson(companyChairmanList));
        }
        String templateKey = null;
        Boolean flag = false;
        if (bean.getExternalWork() == 0 && bean.getStatus() == 1) {
            templateKey = getTemplateKey(checkResult);
            // 启动流程
            if (null == templateKey) {
                factory.close();
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("未找到流程模板");
                return msg;
            }
            if (bean.getOperationCategory() == 3) {
                // 检查审批是否选择或者是否有签名
                Boolean checkApprover = checkApprover(templateKey, bean, approver);
                if (checkApprover) {
                    if (ObjectUtil.checkObjAllFieldsIsNull(approver)) {
                        bean.setStatus(2);
                    } else {
                        flag = true;
                    }
                } else {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("请完成签名或者选择审批人后提交");
                    factory.close(false);
                    return msg;
                }
            } else {
                flag = true;
            }
        } else {
            bean.setOperationCode(entity.getOperationCode());
        }
        Integer value = factory.getMapper(DangerousOperationMapper.class).update(bean);
        if (value > 0) {
            value = updateRelation(bean, factory, value);
        }
        if (value > 0) {
            if (flag) {
                Boolean startAudit = startAudit(bean, user, approver, "流程待审批", "危险作业流程", templateKey);
                if (!startAudit) {
                    deleteKeepFile(fileBean);
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("危险作业流程启动失败");
                    return msg;
                } else {
                    deleteDelFile(fileBean);
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("危险作业提交成功");
                    return msg;
                }
            }
            deleteDelFile(fileBean);
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("危险作业保存成功");
            return msg;
        } else {
            deleteKeepFile(fileBean);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("危险作业修改失败");
            return msg;
        }

    }


    /**
     * 修改危险作业成功后，删除要移除的附件
     *
     * @param fileBean
     */
    public void deleteDelFile(DangerousOperationFile fileBean) {
        // 删除的附件地址
        String delFiles = fileBean.getDelFiles();
        deleteFile(delFiles);
        // 删除的附件预览地址
        String delPreviewFiles = fileBean.getDelPreviewFiles();
        deleteFile(delPreviewFiles);
        // 删除的作业申请人签字附件地址
        String delOperationApplicantFile = fileBean.getOperationApplicantFileDel();
        deleteFile(delOperationApplicantFile);
        //删除的作业执行人签字附件地址
        String delOperationExecutorFile = fileBean.getOperationExecutorFileDel();
        deleteFile(delOperationExecutorFile);
        // 删除的作业指挥人签字附件地址
        String delHoistingCommanderFile = fileBean.getHoistingCommanderFileDel();
        deleteFile(delHoistingCommanderFile);
        //删除的作业监护人签字附件地址
        String delOperationSupervisorFile = fileBean.getOperationSupervisorFileDel();
        deleteFile(delOperationSupervisorFile);
        //删除的作业负责人签字附件地址
        String delPersonInChargeFile = fileBean.getPersonInChargeFileDel();
        deleteFile(delPersonInChargeFile);
        //删除的分析人签字附件地址
        String delAnalystFile = fileBean.getAnalystFileDel();
        deleteFile(delAnalystFile);
        //删除的受教育人签字附件地址
        String delEducatedPersonFile = fileBean.getEducatedPersonFileDel();
        deleteFile(delEducatedPersonFile);
        //删除的教育人签字附件地址
        String delEducatingPeopleFile = fileBean.getEducatingPeopleFileDel();
        deleteFile(delEducatingPeopleFile);
        //删除的送电人签字附件地址
        String delPowerSupplyPersonFile = fileBean.getPowerSupplyPersonFileDel();
        deleteFile(delPowerSupplyPersonFile);
        //删除的停电人签字附件地址
        String delPowerCutPersonFile = fileBean.getPowerCutPersonFileDel();
        deleteFile(delPowerCutPersonFile);
        //删除的完工确认人签字附件地址
        String delCompletionConfirmerFile = fileBean.getCompletionConfirmerFileDel();
        deleteFile(delCompletionConfirmerFile);
        //删除的生产单位负责人签字附件地址
        String managementUnitHeadFileDel = fileBean.getManagementUnitHeadFileDel();
        deleteFile(managementUnitHeadFileDel);
    }

    public void deleteFile(String delFiles) {
        if (StringUtils.isNotEmpty(delFiles)) {
            String[] delArray = delFiles.split("[,，]");
            for (String delUrl : delArray) {
                clientWrapper.deleteFile(delUrl.split("#")[0]);
            }
        }
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        DangerousOperation operation = null;
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String dangerousOperationId = idList.get(0);
                if (StringUtils.isNotEmpty(dangerousOperationId)) {
                    operation = factory.getMapper(DangerousOperationMapper.class).queryOne(dangerousOperationId);
                    if (operation != null && operation.getStatus() == 1) {
                        //新增作业票流程审核通过后，将状态设为2(作业中)
                        operation.setStatus(2);
                    } else if (operation != null && operation.getStatus() == 4) {
                        // 延期作业申请流程审核通过后
                        operation.setStatus(2);
                        //更改危险作业票结束时间
                        Date delayDate = operation.getDelayDate();
                        if (null != operation.getOperationEndTime()) {
                            operation.setOperationEndTime(delayDate);
                        }
                    }
                    factory.getMapper(DangerousOperationMapper.class).update(operation);
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        // TODO 删除走流程审批通过后的流程操作
    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String dangerousOperationId = idList.get(0);
                if (StringUtils.isNotEmpty(dangerousOperationId)) {
                    DangerousOperation operation = factory.getMapper(DangerousOperationMapper.class).queryOne(dangerousOperationId);
                    if (operation != null && operation.getStatus() == 1) {
                        // 新增提交审核不通过，状态改为草稿
                        operation.setStatus(0);
                    } else if (operation != null && operation.getStatus() == 4) {
                        // 延期申请提交审核不通过
                        // 改回未延期
                        operation.setDelay(0);
                        // 状态改为作业中
                        operation.setStatus(2);
                    }
                    factory.getMapper(DangerousOperationMapper.class).update(operation);
                    factory.close();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(DangerousOperationServiceImpl.class.getName(), this);
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
